-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathblockcachevfs.c
7833 lines (7098 loc) · 220 KB
/
blockcachevfs.c
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
#if !defined(__WIN32__) && (defined(WIN32) || defined(_WIN32))
# define __WIN32__
#endif
#include "sqlite3.h"
#include "blockcachevfs.h"
#include "bcv_int.h"
#include <string.h>
#include <assert.h>
#include <openssl/hmac.h>
#include <openssl/sha.h>
#include <openssl/md5.h>
typedef struct BcvFileCache BcvFileCache;
typedef struct BcvKVStore BcvKVStore;
typedef struct BcvfsFile BcvfsFile;
typedef struct BcvMRULink BcvMRULink;
typedef struct BcvProxyFile BcvProxyFile;
typedef struct BcvWrapper BcvWrapper;
typedef struct CacheEntry CacheEntry;
typedef struct Container Container;
typedef struct BcvDbPath BcvDbPath;
typedef struct Mutex Mutex;
#define BCV_POLL_OPTION "bcv_poll"
#define BCV_AUTH_OPTION "bcv_auth"
#define BCV_DEFAULT_POLL_OPTION 0
#define BCV_DEFAULT_CACHESIZE (1024*1024*1024)
#define BCV_DEFAULT_NREQUEST 10
#define BCVFS_MAX_AUTH_RETRIES 10
#define WAL_CHECKPOINTER_LOCK 1
#define BCV_PORTNUMBER_FILE "portnumber.bcv"
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
#ifdef __WIN32__
# include <windows.h>
# include <direct.h>
# define BCV_PATH_SEPARATOR "\\"
# define osMkdir(x,y) mkdir(x)
#else
# include <pthread.h>
# define BCV_PATH_SEPARATOR "/"
# define osMkdir(x,y) mkdir(x,y)
#endif
#define BCV_FCNTL_FD 82460214
/*
** Mutex/condition type. This type and its methods encapsulate the
** platform dependent thread-related things in this file. Methods are:
**
** bcvfsMutexInit()
** bcvfsMutexShutdown()
** bcvfsMutexEnter()
** bcvfsMutexLeave()
** bcvfsMutexCondWait()
** bcvfsMutexCondSignal()
*/
struct Mutex {
int bHeld; /* True if mutex is held */
#ifdef __WIN32__
CRITICAL_SECTION mut;
CONDITION_VARIABLE cond;
#else
pthread_mutex_t mut;
pthread_cond_t cond;
#endif
};
/*
** An array of structures of this type is maintained by proxy VFS clients
** while reading from the database. See comments above BcvProxyFile for
** details.
*/
struct BcvMRULink {
int iNext;
int iPrev;
};
/*
** aMRU:
** Each time a new cache-file map is obtained from the daemon (either
** at the start of a read transaction or because a missing block was
** requested) a new, zeroed, array containing one entry for each block
** in the database is allocated here.
**
** As the read operation progresses, the elements of the array are organized
** into a doubly-linked list in order from most-recently to least-recently
** used. Integer values BcvMRULink.iNext and BcvMRULink.iPrev are used
** in place of pointers - 0 is a null pointer, any value X greater than
** 0 is interpreted as a pointer to aMRU[X-1].
**
** iMRU:
** aMRU style "pointer" to element the of aMRU representing the most
** recently used block. A value of 0 is a null pointer, any value X greater
** than 0 is interpreted as a pointer to aMRU[X-1].
*/
struct BcvProxyFile {
BCV_SOCKET_TYPE fdProxy;
char *zStorage;
char *zAccount;
char *zContainer;
int szBlk;
BcvMessage *pMap;
BcvMRULink *aMRU; /* Array of pMap->u.read_r.nBlk elements */
int iMRU; /* Index of most recently used block */
char *zAuth;
BcvIntKey *pKey; /* Encryption key, if any */
};
struct BcvKVStore {
char *zETag;
char *zDate; /* Value of 'date' for bcv_kv_meta */
char *zLastModified; /* Value of 'last-modified' for bcv_kv_meta */
sqlite3 *db;
};
/*
** File object for this VFS. This VFS handles 3 separate types of files:
**
** Database files - (pPath!=0 && pCacheFile!=0)
** Wal files - (pPath!=0 && pCacheFile==0)
** Pass thru files - (pPath==0 && pCacheFile==0)
**
** The final category includes all files that are not cloud database
** files or their associated local wal files.
**
** pFile:
** All file types - temp files, wal files and database files - store a
** pointer to the "real" file-handle here.
**
** zFile:
** Actual file name for BcvfsFile.pFile.
**
** lockMask:
** Mask of shm-locks held by the connetion. If either an exclusive or
** shared lock is held on a locking-slot, the corresponding bit is set
** in this variable. There is no distinction made between shared and
** exclusive locks, only between locked and unlocked.
**
** bHoldCkpt:
** If set, do not release the CHECKPOINTER lock in xShmLock when
** requested to. This is used as part of uploading databases.
*/
struct BcvfsFile {
sqlite3_file base;
sqlite3 **ppDb; /* From SQLITE_FCNTL_PDB */
sqlite3_bcvfs *pFs; /* VFS that owns this object */
sqlite3_file *pFile; /* Open file descriptor */
char *zLocalPath; /* Full local path for pFile */
int bIsMain; /* True if opened with MAIN_DB */
BcvDbPath *pPath;
sqlite3_file *pCacheFile;
char *zClientId; /* Set by "PRAGMA bcv_client=?" */
/* Used in proxy mode only */
BcvProxyFile p;
i64 iFileDbId; /* Database id for db and wal files */
Container *pCont; /* VFS-wide container object */
Manifest *pMan; /* When transaction is open, manifest */
ManifestDb *pManDb; /* When transaction is open, manifest-db */
u32 lockMask; /* Mask of shm-locks currently held */
int eLock; /* Legacy lock held */
int bHoldCkpt; /* True to not release CHECKPOINTER lock */
BcvKVStore kv;
/* Used when fetching a block - see bcvfsFetchBlock(). And by
** sqlite3_bcvfs_upload(). */
CacheEntry *pEntry;
int rc;
BcvfsFile *pNextFile;
};
#define BCVFS_PASSTHRU_FILE 0
#define BCVFS_WAL_FILE 1
#define BCVFS_DATABASE_FILE 2
#define BCVFS_NO_FILE 3
#define BCVFS_PROXY_FILE 4
/*
** Macros to enter and leave the VFS mutex.
*/
#define ENTER_VFS_MUTEX (bcvfsMutexEnter(&pFs->mutex))
#define LEAVE_VFS_MUTEX (bcvfsMutexLeave(&pFs->mutex))
#define CHECK_VFS_MUTEX (assert( pFs->mutex.bHeld ))
#define BCVFS_FIRST_LOCAL_ID (i64)(0xFFFFFFFF - 1000000)
/*
** VFS handle.
**
** iNextLocalId:
** Next id value to assign to a local db created by sqlite3_bcvfs_copy().
**
** pFileList:
** This is always NULL if the VFS is a proxy VFS. Otherwise, it is the
** head of a linked list containing all file handles open on database
** files.
*/
struct sqlite3_bcvfs {
sqlite3_vfs base;
int nRef; /* Number of connected clients+prefetchers */
char *zName; /* Name of VFS created */
char *zPortnumber; /* Where to connect, for a proxy VFS */
char *zCacheFile; /* Full path to cache file */
int nRequest; /* SQLITE_BCV_NREQUEST value */
int nHttpTimeout; /* SQLITE_BCV_HTTPTIMEOUT value */
i64 iNextLocalId;
BcvfsFile *pFileList;
int nOnDemand; /* Current outstanding on-demand requests */
/* Log callback */
void *pLogCtx;
int mLog;
void(*xLog)(void*, int, const char*);
int bCurlVerbose;
/* Authentication callback */
void *pAuthCtx;
int(*xAuth)(void*, const char*, const char*, const char*, char**);
/* Active prefetches */
sqlite3_prefetch *pPrefetch;
BcvCommon c; /* Hash tables etc. */
Mutex mutex; /* Mutex/condition variable object */
};
struct BcvDbPath {
char *zContainer;
char *zDatabase;
};
#define BCV_DATABASE_SCHEMA \
"CREATE TABLE IF NOT EXISTS block(\n" \
" cachefilepos INTEGER PRIMARY KEY,\n" \
" blockid BLOB,\n" \
" container TEXT,\n" \
" db INTEGER,\n" \
" dbpos INTEGER,\n" \
" dbversion INTEGER,\n" \
" CHECK (blockid IS NOT NULL OR container IS NOT NULL)" \
");" \
"CREATE TABLE IF NOT EXISTS container(\n" \
" name TEXT PRIMARY KEY,\n" \
" storage TEXT,\n" \
" user TEXT,\n" \
" container TEXT,\n" \
" manifest BLOB,\n" \
" etag \n" \
");" \
"CREATE TABLE IF NOT EXISTS config(" \
" k TEXT PRIMARY KEY,\n" \
" v \n" \
");" \
"CREATE TABLE IF NOT EXISTS pinned(" \
" container TEXT,\n" \
" database TEXT,\n" \
" PRIMARY KEY(container, database) \n" \
");"
/*
** bcvfsMutexInit()
** bcvfsMutexShutdown()
** bcvfsMutexEnter()
** bcvfsMutexLeave()
** bcvfsMutexCondWait()
** bcvfsMutexCondSignal()
*/
static int bcvfsCantopenError(){
return SQLITE_CANTOPEN;
}
#define BCVFS_CANTOPEN bcvfsCantopenError()
/*
** Initialize a new Mutex object.
*/
static int bcvfsMutexInit(Mutex *p){
memset(p, 0, sizeof(Mutex));
#ifdef __WIN32__
InitializeCriticalSection(&p->mut);
InitializeConditionVariable(&p->cond);
#else
pthread_mutex_init(&p->mut, 0);
pthread_cond_init(&p->cond, 0);
#endif
return SQLITE_OK;
}
/*
** Shutdown a mutex object.
*/
static void bcvfsMutexShutdown(Mutex *p){
#ifdef __WIN32__
DeleteCriticalSection(&p->mut);
#else
pthread_mutex_destroy(&p->mut);
pthread_cond_destroy(&p->cond);
#endif
memset(p, 0, sizeof(Mutex));
}
/*
** Enter the mutex.
*/
static void bcvfsMutexEnter(Mutex *p){
#ifdef __WIN32__
EnterCriticalSection(&p->mut);
#else
pthread_mutex_lock(&p->mut);
#endif
assert( p->bHeld==0 );
p->bHeld = 1;
}
/*
** Leave the mutex.
*/
static void bcvfsMutexLeave(Mutex *p){
assert( p->bHeld );
p->bHeld = 0;
#ifdef __WIN32__
LeaveCriticalSection(&p->mut);
#else
pthread_mutex_unlock(&p->mut);
#endif
}
/*
** The mutex must be held when this function is called. It releases the
** mutex and then blocks, waiting for the condition to by signalled by
** a call to bcvfsMutexCondSignal.
*/
static void bcvfsMutexCondWait(Mutex *p){
assert( p->bHeld );
p->bHeld = 0;
#ifdef __WIN32__
SleepConditionVariableCS(&p->cond, &p->mut, INFINITE);
#else
pthread_cond_wait(&p->cond, &p->mut);
#endif
p->bHeld = 1;
}
/*
** Unblock all threads waiting in bcvfsMutexCondWait().
*/
static void bcvfsMutexCondSignal(Mutex *p){
#ifdef __WIN32__
WakeAllConditionVariable(&p->cond);
#else
pthread_cond_broadcast(&p->cond);
#endif
}
/*
** Return the type of a file object.
*/
static int bcvfsFileType(BcvfsFile *pFile){
assert( (pFile->pPath==0 && pFile->pCacheFile==0)
|| (pFile->pPath!=0 && pFile->pCacheFile==0)
|| (pFile->pPath!=0 && pFile->pCacheFile!=0)
);
if( pFile->pFile==0 ) return BCVFS_NO_FILE;
if( pFile->pPath==0 ) return BCVFS_PASSTHRU_FILE;
if( pFile->pCacheFile==0 ) return BCVFS_WAL_FILE;
if( pFile->p.zStorage ) return BCVFS_PROXY_FILE;
return BCVFS_DATABASE_FILE;
}
static int bcvfsIsSafeChar(char c){
if( c>='0' && c<='9' ) return 1;
if( c>='a' && c<='z' ) return 1;
if( c>='A' && c<='Z' ) return 1;
if( c=='_' || c=='-' || c=='.' ) return 1;
return 0;
}
#if 0
static void bcvfsPutText(char **pz, const char *zIn){
int nIn = bcvStrlen(zIn);
char *z = *pz;
memcpy(z, zIn, nIn+1);
*pz = &z[nIn];
}
static void bcvfsPutFormat(char **pz, const char *zFmt, ...){
char *z = *pz;
va_list ap;
va_start(ap, zFmt);
sqlite3_vsnprintf(100000, z, zFmt, ap);
z += strlen(z);
*pz = z;
va_end(ap);
}
#endif
static void bcvfsPutEscaped(char **pz, const char *zIn){
const char aHex[16] = {
'0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'A', 'B', 'C', 'D', 'E', 'F',
};
char *pOut = *pz;
const char *pIn;
for(pIn=zIn; *pIn; pIn++){
char c = *pIn;
if( bcvfsIsSafeChar(c) ){
*pOut++ = c;
}else{
*pOut++ = '%';
*pOut++ = aHex[(c>>4) & 0x0F];
*pOut++ = aHex[c & 0x0F];
}
}
*pOut = '\0';
*pz = pOut;
}
/*
** Attempt to decompose the path in zName into its components and allocate
** and return the corresponding BcvDbPath object. There are three forms that
** the path may take:
**
** /
** /CONTAINER
** /CONTAINER/DATABASE
**
** If successful, set (*pp) to point to a new object and return SQLITE_OK.
** Otherwise, if an error occurs, set (*pp) to NULL and return an SQLite
** error code.
*/
static int bcvfsDecodeName(
sqlite3_bcvfs *pFs,
const char *zName,
BcvDbPath **pp
){
int rc = SQLITE_OK;
int nCopy = bcvStrlen(zName);
int nAlloc;
BcvDbPath *pRet = 0;
nAlloc = sizeof(BcvDbPath) + nCopy+1 + bcvStrlen(pFs->c.zDir) + nCopy*3+1;
pRet = (BcvDbPath*)bcvMallocRc(&rc, nAlloc);
if( pRet ){
char *z = (char*)&pRet[1];
memcpy(z, zName, nCopy);
if( *z!='/' && *z!='\\' ){
rc = SQLITE_ERROR;
}else{
z++;
if( *z ){
/* not form 1 - "/" */
pRet->zContainer = z;
while( *z!='\0' && *z!='/' && *z!='\\' ) z++;
if( *z!='\0' ){
/* not form 2 - "/CONTAINER" */
*z = '\0';
z++;
pRet->zDatabase = z;
while( *z!='\0' && *z!='/' && *z!='\\' ) z++;
if( *z!='\0' ) rc = SQLITE_ERROR;
}
z++;
}
}
if( rc!=SQLITE_OK ){
sqlite3_free(pRet);
pRet =0;
}
}
*pp = pRet;
return rc;
}
static void bcvfsMaskLog(sqlite3_bcvfs *pFs, u32 mask, const char *zFmt, ...){
va_list ap;
va_start(ap, zFmt);
if( pFs->mLog & mask ){
char *zMsg = sqlite3_vmprintf(zFmt, ap);
pFs->xLog(pFs->pLogCtx, mask, zMsg);
sqlite3_free(zMsg);
}
va_end(ap);
}
#define bcvfsUploadLog(pFs, zFmt, ...) \
bcvfsMaskLog(pFs, SQLITE_BCV_LOG_UPLOAD, zFmt, __VA_ARGS__)
#define bcvfsCleanupLog(pFs, zFmt, ...) \
bcvfsMaskLog(pFs, SQLITE_BCV_LOG_CLEANUP, zFmt, __VA_ARGS__)
#define bcvfsEventLog(pFs, zFmt, ...) \
bcvfsMaskLog(pFs, SQLITE_BCV_LOG_EVENT, zFmt, __VA_ARGS__)
/*
** Type passed between bcvfsFetchManifest() and callback function
** bcvfsFetchManifestCb() via the (void*) context pointer.
*/
typedef struct ManifestCb ManifestCb;
struct ManifestCb {
int rc;
char *zErr;
Manifest *pMan;
};
/*
** Fetch callback used by bcvfsFetchManifest().
*/
static void bcvfsFetchManifestCb(
void *pCtx,
int rc, char *zETag,
const u8 *aData, int nData,
const u8 *aHdrs, int nHdrs
){
ManifestCb *pCb = (ManifestCb*)pCtx;
char *zErr = 0;
if( rc==SQLITE_OK ){
rc = bcvManifestParseCopy(aData, nData, zETag, &pCb->pMan, &zErr);
}else if( zETag ){
zErr = sqlite3_mprintf("%s", zETag);
}
assert( pCb->rc==SQLITE_OK && pCb->zErr==0 );
pCb->rc = rc;
pCb->zErr = zErr;
}
/*
** Use the pDisp/pBcv dispatcher/container pair to download the manifest
** file. If successful, deserialize it, store the result in output
** variable (*ppMan) and return SQLITE_OK.
**
** Or, if an error occurs, set (*ppMan) to NULL and return either an SQLite
** or HTTPS error code. In this case, if pzErr is not NULL, then (*pzErr)
** may also be set to point to a buffer containing an error message. It
** is the responsibility fo the caller to eventually free this buffer
** using sqlite3_free().
*/
static int bcvfsFetchManifest(
BcvDispatch *pDisp,
BcvContainer *pBcv,
Manifest **ppMan,
char **pzErr
){
ManifestCb cb = {0, 0, 0};
int rc = bcvDispatchFetch(
pDisp, pBcv, BCV_MANIFEST_FILE, 0, 0, (void*)&cb, bcvfsFetchManifestCb
);
if( rc==SQLITE_OK ){
rc = bcvDispatchRunAll(pDisp);
}
if( cb.pMan==0 && rc==SQLITE_OK ){
rc = cb.rc;
}
assert( cb.pMan || rc!=SQLITE_OK );
*ppMan = cb.pMan;
*pzErr = cb.zErr;
return rc;
}
/*
** Type passed between bcvfsFetchManifest() and callback function
** bcvfsFetchManifestCb() via the (void*) context pointer.
*/
typedef struct BlockCb BlockCb;
struct BlockCb {
int rc;
BcvfsFile *pFile;
CacheEntry *pEntry;
};
/*
** The first argument points to a NAMEBYTES byte buffer
** containing a block-id. Format the block-id as text and write it to
** buffer aBuf[], which must be at leat BCV_FILESYSTEM_BLOCKID_BYTES
** in size.
*/
void bcvfsBlockidToText(const u8 *pBlk, int nBlk, char *aBuf){
hex_encode(pBlk, nBlk, aBuf, 1);
memcpy(&aBuf[nBlk*2], ".bcv", 5);
}
/*
** Fetch callback used by bcvfsFetchBlock().
*/
static void bcvfsFetchBlockCb(
void *pCtx,
int rc, char *zETag,
const u8 *aData, int nData,
const u8 *aHdrs, int nHdrs
){
BcvfsFile *pFile = (BcvfsFile*)pCtx;
if( rc==SQLITE_OK ){
i64 iOff = (pFile->pEntry->iPos * pFile->pFs->c.szBlk);
rc = bcvWritefile(pFile->pCacheFile, aData, nData, iOff);
}else{
/* TODO: log the error somehow */
}
pFile->rc = rc;
}
/*
** Download the block specified by pEntry->aName to cache-file slot
** pEntry->iPos. Return SQLITE_OK if successful, or an error code
** otherwise.
*/
static int bcvfsFetchBlock(
BcvfsFile *pFile,
BcvDispatch *pDisp,
BcvContainer *pBcv,
int iBlk,
CacheEntry *pEntry
){
sqlite3_bcvfs *pFs = pFile->pFs;
int rc = SQLITE_OK;
char aName[BCV_MAX_FSNAMEBYTES];
pFile->pEntry = pEntry;
pFile->rc = SQLITE_OK;
bcvfsBlockidToText(pEntry->aName, pEntry->nName, aName);
ENTER_VFS_MUTEX; {
pFs->nOnDemand++;
} LEAVE_VFS_MUTEX;
rc = bcvDispatchLogmsg(pDisp,
"demand %d of %s", iBlk, pFile->pPath->zDatabase
);
if( rc==SQLITE_OK ){
rc = bcvDispatchFetch(pDisp,pBcv,aName,0,0,(void*)pFile,bcvfsFetchBlockCb);
}
if( rc==SQLITE_OK ){
rc = bcvDispatchRunAll(pDisp);
}
rc = (rc==SQLITE_OK ? pFile->rc : rc);
ENTER_VFS_MUTEX; {
pFs->nOnDemand--;
} LEAVE_VFS_MUTEX;
return rc;
}
/*
** Search the manifest passed as the first argument for a database with
** display name zDb. If one is found, return a pointer to it. Otherwise,
** return NULL.
*/
ManifestDb *bcvfsFindDatabase(Manifest *pMan, const char *zDb, int nDb){
int ii;
if( nDb<0 ){
nDb = bcvStrlen(zDb);
}
for(ii=0; ii<pMan->nDb; ii++){
ManifestDb *pDb = &pMan->aDb[ii];
if( strlen(pDb->zDName)==nDb && memcmp(pDb->zDName, zDb, nDb)==0 ){
return pDb;
}
}
return 0;
}
/*
** Search the manifest supplied as the first argument for a database with
** database id iDbId. If it is found, return a pointer to the ManifestDb
** object. Otherwise, if there is no such db, return a NULL pointer.
*/
static ManifestDb *bcvfsFindDatabaseById(Manifest *pMan, i64 iDbId){
int ii;
for(ii=0; ii<pMan->nDb; ii++){
ManifestDb *pDb = &pMan->aDb[ii];
if( pDb->iDbId==iDbId ){
return pDb;
}
}
return 0;
}
/*
** Return the current MRU array to send to the daemon.
*/
static u32 *bcvfsProxyMRUArray(BcvProxyFile *p, u32 *pn){
int nRet = 0;
u32 *aRet = 0;
BcvMRULink *aMRU = p->aMRU;
if( aMRU && p->iMRU ){
aRet = (u32*)&aMRU[p->pMap->u.read_r.nBlk];
BcvMRULink *pLink = &aMRU[p->iMRU-1];
u32 *aRet = (u32*)&aMRU[p->pMap->u.read_r.nBlk];
while( 1 ){
aRet[nRet++] = pLink - aMRU;
if( pLink->iNext==0 ) break;
pLink = &aMRU[pLink->iNext-1];
assert( nRet<p->pMap->u.read_r.nBlk );
}
}
*pn = (u32)nRet;
return aRet;
}
/*
** Move block iBlk to the start of the MRU list.
*/
static void bcvfsProxyMRUAdd(BcvProxyFile *p, int iBlk){
if( p->iMRU!=iBlk+1 ){
BcvMRULink *aMRU = p->aMRU;
/* Remove the block from its existing position, if any */
if( aMRU[iBlk].iNext ){
aMRU[ aMRU[iBlk].iNext-1 ].iPrev = aMRU[iBlk].iPrev;
}
if( aMRU[iBlk].iPrev ){
aMRU[ aMRU[iBlk].iPrev-1 ].iNext = aMRU[iBlk].iNext;
}
/* Add the block to the head of the list */
aMRU[iBlk].iPrev = 0;
if( p->iMRU ){
aMRU[iBlk].iNext = p->iMRU;
aMRU[p->iMRU-1].iPrev = iBlk+1;
}
p->iMRU = iBlk+1;
{
u32 dummy = 0;
bcvfsProxyMRUArray(p, &dummy);
}
}
}
static void bcvfsProxyCloseTransactionIf(BcvfsFile *pFile){
if( pFile->lockMask==0 && pFile->p.pMap ){
BcvMessage msg;
memset(&msg, 0, sizeof(BcvMessage));
msg.eType = BCV_MESSAGE_END;
msg.u.end.aMru = bcvfsProxyMRUArray(&pFile->p, &msg.u.end.nMru);
bcvSendMsg(pFile->p.fdProxy, &msg);
sqlite3_free(pFile->p.pMap);
sqlite3_free(pFile->p.aMRU);
pFile->p.pMap = 0;
pFile->p.aMRU = 0;
}
}
static void bcvKVStoreFree(BcvKVStore *pKv){
sqlite3_close_v2(pKv->db);
sqlite3_free(pKv->zETag);
sqlite3_free(pKv->zDate);
sqlite3_free(pKv->zLastModified);
memset(pKv, 0, sizeof(BcvKVStore));
}
static void bcvfsCloseFile(sqlite3_file *pFile){
if( pFile && pFile->pMethods ){
pFile->pMethods->xClose(pFile);
}
}
static int bcvfsClose(sqlite3_file *pFd){
BcvfsFile *pFile = (BcvfsFile*)pFd;
sqlite3_bcvfs *pFs = pFile->pFs;
if( pFile->pCont ){
ENTER_VFS_MUTEX; {
/* Remove the BcvfsFile object from the sqlite3_bcvfs.pFileList list */
BcvfsFile **pp;
for(pp=&pFs->pFileList; *pp; pp=&(*pp)->pNextFile){
if( *pp==pFile ){
*pp = pFile->pNextFile;
break;
}
}
pFile->pCont->nClient--;
bcvManifestDeref(pFile->pMan);
} LEAVE_VFS_MUTEX;
}
ENTER_VFS_MUTEX; {
pFile->pFs->nRef--;
} LEAVE_VFS_MUTEX;
bcv_close_socket(pFile->p.fdProxy);
sqlite3_free(pFile->p.zStorage);
sqlite3_free(pFile->p.zAccount);
sqlite3_free(pFile->p.zContainer);
sqlite3_free(pFile->p.zAuth);
bcvIntEncryptionKeyFree(pFile->p.pKey);
pFile->lockMask = 0;
bcvKVStoreFree(&pFile->kv);
bcvfsProxyCloseTransactionIf(pFile);
bcvCloseLocal(pFile->pCacheFile);
bcvfsCloseFile(pFile->pFile);
sqlite3_free(pFile->zLocalPath);
sqlite3_free(pFile->pPath);
sqlite3_free(pFile->zClientId);
return SQLITE_OK;
}
static u32 bcvfsBlockHash(const u8 *pBlk, int nBlk){
return bcvGetU32(&pBlk[4]);
}
/*
** The cache-entry passed as the second argument is guaranteed to be
** part of the LRU list of the VFS passed as the first argument. Remove
** it from the list.
*/
static void bcvfsLruRemove(BcvCommon *p, CacheEntry *pEntry){
assert( p->bDaemon || pEntry->nRef==0 );
assert( pEntry->pLruPrev || pEntry==p->pLruFirst );
assert( pEntry->pLruNext || pEntry==p->pLruLast );
assert( pEntry->pLruPrev==0 || pEntry->pLruPrev->pLruNext==pEntry );
assert( pEntry->pLruNext==0 || pEntry->pLruNext->pLruPrev==pEntry );
if( pEntry->pLruPrev ){
pEntry->pLruPrev->pLruNext = pEntry->pLruNext;
}else{
p->pLruFirst = pEntry->pLruNext;
}
if( pEntry->pLruNext ){
pEntry->pLruNext->pLruPrev = pEntry->pLruPrev;
}else{
p->pLruLast = pEntry->pLruPrev;
}
pEntry->pLruNext = pEntry->pLruPrev = 0;
}
/*
** If the cache entry passed as the second argument should be a part
** of the LRU list, remove it. A cache entry "should" be part of said
** list if:
**
** a) there are no references,
** b) there are no pins, and
** c) the block is not dirty.
*/
void bcvfsLruRemoveIf(BcvCommon *p, CacheEntry *pEntry){
if( (pEntry->nRef==0 || p->bDaemon) && pEntry->bDirty==0 ){
bcvfsLruRemove(p, pEntry);
}
}
/*
** The cache-entry passed as the second argument is guaranteed NOT to
** be part of the LRU list of the VFS passed as the first argument. Add
** it to the list.
*/
void bcvfsLruAdd(BcvCommon *p, CacheEntry *pEntry){
assert( pEntry->pLruNext==0 && pEntry->pLruPrev==0 );
assert( p->pLruFirst!=pEntry && p->pLruLast!=pEntry );
assert( p->bDaemon || pEntry->nRef==0 );
assert( pEntry->bDirty==0 );
pEntry->iLruTick = ++p->iLruTick;
if( p->pLruFirst ){
pEntry->pLruPrev = p->pLruLast;
p->pLruLast->pLruNext = pEntry;
p->pLruLast = pEntry;
}else{
p->pLruFirst = p->pLruLast = pEntry;
}
}
void bcvfsLruAddIf(BcvCommon *p, CacheEntry *pEntry){
if( (p->bDaemon || pEntry->nRef==0) && pEntry->bDirty==0 ){
bcvfsLruAdd(p, pEntry);
}
}
/*
** Search the hash table for a cache entry for the specified block-id.
** If it is found, return a pointer to it.
*/
CacheEntry *bcvfsHashFind(BcvCommon *p, const u8 *pBlk, int nBlk){
CacheEntry *pRet = 0;
u32 iHash = bcvfsBlockHash(pBlk, nBlk) % p->nHash;
pRet = p->aHash[iHash];
while( pRet && memcmp(pRet->aName, pBlk, nBlk) ){
pRet = pRet->pHashNext;
}
return pRet;
}
/*
** Add the entry passed as the second argument to the hash table. This
** function assumes that the entry is not already in the hash table.
*/
void bcvfsHashAdd(BcvCommon *p, CacheEntry *pEntry){
u32 iHash = bcvfsBlockHash(pEntry->aName, pEntry->nName) % p->nHash;
pEntry->pHashNext = p->aHash[iHash];
p->aHash[iHash] = pEntry;
}
/*
** Remove the entry passed as the second argument from the hash table, if
** it is currently a part of it.
*/
void bcvfsHashRemove(BcvCommon *p, CacheEntry *pEntry){
CacheEntry **pp;
u32 iHash = bcvfsBlockHash(pEntry->aName, pEntry->nName) % p->nHash;
for(pp=&p->aHash[iHash]; *pp; pp=&(*pp)->pHashNext){
if( *pp==pEntry ){
*pp = pEntry->pHashNext;
break;
}
}
pEntry->pHashNext = 0;
}
/*
** Add the cache-entry to the unused list.
*/
void bcvfsUnusedAdd(BcvCommon *p, CacheEntry *pEntry){
int iPos = pEntry->iPos;
memset(pEntry, 0, sizeof(CacheEntry));
pEntry->iPos = iPos;
pEntry->pHashNext = p->pUnused;
p->pUnused = pEntry;
}
/*
** Decrement the ref-count on object pEntry. If the final ref-count is
** zero, add pEntry to the LRU list.
*/
void bcvfsEntryUnref(BcvCommon *p, CacheEntry *pEntry){
assert( pEntry->nRef>0 );
pEntry->nRef--;
bcvfsLruAddIf(p, pEntry);
}
/*
** Write an entry into the "block" table for the cache entry
** passed as the second argument.
*/
static int bcvfsWriteBlock(
sqlite3_bcvfs *pFs,
BcvfsFile *pFile,
int iBlk,
CacheEntry *pEntry
){
int rc = SQLITE_OK;
sqlite3_stmt *pStmt = 0;
CHECK_VFS_MUTEX;
pStmt = pFs->c.pInsertBlock;
sqlite3_bind_int(pStmt, 1, pEntry->iPos);
if( pEntry->bDirty ){
sqlite3_bind_text(pStmt, 3, pFile->pCont->zName, -1, SQLITE_STATIC);
sqlite3_bind_int64(pStmt, 4, pFile->iFileDbId);
sqlite3_bind_int(pStmt, 5, iBlk);
sqlite3_bind_int(pStmt, 6, 0);
}else{
assert( pEntry->aName && pEntry->nName>0 );
sqlite3_bind_blob(pStmt, 2, pEntry->aName, pEntry->nName, SQLITE_STATIC);
}
sqlite3_step(pStmt);
rc = sqlite3_reset(pStmt);
sqlite3_clear_bindings(pStmt);
return rc;
}
CacheEntry *bcvfsAllocCacheEntry(int *pRc, BcvCommon *p){
CacheEntry *pRet = 0;
if( p->pUnused ){
pRet = p->pUnused;
p->pUnused = pRet->pHashNext;