-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsqlfs.c
More file actions
2099 lines (1900 loc) · 71.3 KB
/
Copy pathsqlfs.c
File metadata and controls
2099 lines (1900 loc) · 71.3 KB
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
// Implements a filesystem in an SQLite3 database.
//
// Naming conventios used in this file:
//
// - Function names starting with "sqlfs_" indicate exported functions with a
// declaration in sqlfs.h (which is also where they are documented).
// - Helper function names starting with "sql_" indicate those functions
// (mainly) execute SQL statements. They will be declared static.
// - Other helper functions use no particular prefix. They will also be static.
//
// Conventions on error propagation:
//
// We use a mix of CHECK() failures (which abort execution immediately) and
// propagating errors back to the client.
//
// - CHECK() failures are used for conditions that shouldn't happen and most
// read-only query failures. The rationale is that we cannot reasonably
// recover from those, and if the database is not readable, we cannot provide
// any useful functionality, so we might as well crash immediately.
// - Error propagation is used for failure of database updates. The rationale
// is that it's possible to mount a read-only database, or for database
// writes to fail (e.g., because the disk is full). We shouldn't crash, but
// still support read-only functionality instead. Database write errors are
// returned as errno EIO, unless otherwise specified.
//
// All database updates are performed within an exclusive transaction. This
// guarantees that if a CHECK() failure occurs halfway through an update, the
// transaction will be rolled back and the database will be left in a consistent
// state.
//
// We use savepoints to allow transactions to be nested. Each call to
// sql_savepoint() must be paired with a later call to sql_release_savepoint().
// If an operation failed and the changes made in the transaction should be
// rolled back, call sql_rollback_to_savepoint() to discard those changes, just
// before calling sql_release_savepoint().
#include "sqlfs.h"
#include <errno.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <time.h>
#include <unistd.h>
#include <sqlite3.h>
#include "logging.h"
// Log a message, prefixed with a file name and line number.
// Used for debug-logging throughout this file.
#define DLOG(fmt, ...) LOG("[%s:%d] " fmt, __FILE__, __LINE__, __VA_ARGS__)
#define NANOS_PER_SECOND 1000000000
// Minimum/maximum supported SQLCipher major version.
//
// The maximum is also capped by the current SQLCipher library version (see
// sqlfs_get_sqlcipher_version()) so in principle we don't need the upper limit,
// but this way we won't unintentionally create files incompatible with v4.
#define MIN_CIPHER_COMPAT 3
#define MAX_CIPHER_COMPAT 4
enum statements {
STMT_SAVEPOINT,
STMT_RELEASE_SAVEPOINT,
STMT_ROLLBACK_TO_SAVEPOINT,
STMT_STAT,
STMT_STAT_ENTRY,
STMT_LOOKUP,
STMT_UPDATE_NLINK,
STMT_INSERT_METADATA,
STMT_UPDATE_METADATA,
STMT_DELETE_METADATA,
STMT_INSERT_DIRENTRIES,
STMT_COUNT_DIRENTRIES,
STMT_DELETE_DIRENTRIES,
STMT_DELETE_DIRENTRIES_BY_NAME,
STMT_REPARENT_DIRECTORY,
STMT_READ_DIRENTRIES,
STMT_READ_DIRENTRIES_START,
STMT_RENAME,
STMT_READ_FILEDATA,
STMT_UPDATE_FILEDATA,
STMT_DELETE_FILEDATA,
NUM_STATEMENTS };
// SQL strings for prepared statements. This could just be an array of strings,
// but including the `id` allows us to verify that array indices correspond one-
// to-one with the enumerators above, as a sanity-check.
//
// For each stament of the form STMT_XXX, we also define the query parameter
// indices (for use with sqlite3_bind()) as PARAM_XXX_YYY, and the projection
// column indices (for use with sqlite3_column()) as COL_XXX_ZZZ. Note that
// query parameters are indexed starting from 1, while projection columns are
// indexed from 0 instead!
static const struct statement {
int id;
const char *sql;
} statements[NUM_STATEMENTS] = {
{ STMT_SAVEPOINT,
"SAVEPOINT tx" },
{ STMT_RELEASE_SAVEPOINT,
"RELEASE SAVEPOINT tx" },
{ STMT_ROLLBACK_TO_SAVEPOINT,
"ROLLBACK TO SAVEPOINT tx" },
{ STMT_STAT,
#define PARAM_STAT_INO 1
#define COL_STAT_INO 0
#define COL_STAT_MODE 1
#define COL_STAT_NLINK 2
#define COL_STAT_UID 3
#define COL_STAT_GID 4
#define COL_STAT_SIZE 5
#define COL_STAT_BLKSIZE 6
#define COL_STAT_MTIME 7
#define SELECT_METADATA "SELECT ino, mode, nlink, uid, gid, size, blksize, mtime FROM metadata"
SELECT_METADATA " WHERE ino = ?" },
{ STMT_STAT_ENTRY,
#define PARAM_STAT_ENTRY_DIR_INO 1
#define PARAM_STAT_ENTRY_ENTRY_NAME 2
SELECT_METADATA " INNER JOIN direntries ON ino = entry_ino WHERE dir_ino = ? AND entry_name = ?" },
{ STMT_LOOKUP,
#define PARAM_LOOKUP_DIR_INO 1
#define PARAM_LOOKUP_ENTRY_NAME 2
#define COL_LOOKUP_ENTRY_INO 0
#define COL_LOOKUP_ENTRY_TYPE 1
"SELECT entry_ino, entry_type FROM direntries WHERE dir_ino = ? AND entry_name = ?" },
{ STMT_UPDATE_NLINK,
#define PARAM_UPDATE_NLINK_ADD_LINKS 1
#define PARAM_UPDATE_NLINK_INO 2
"UPDATE metadata SET nlink = nlink + ? WHERE ino = ?" },
{ STMT_INSERT_METADATA,
#define PARAM_INSERT_METADATA_MODE 1
#define PARAM_INSERT_METADATA_NLINK 2
#define PARAM_INSERT_METADATA_UID 3
#define PARAM_INSERT_METADATA_GID 4
#define PARAM_INSERT_METADATA_MTIME 5
#define PARAM_INSERT_METADATA_SIZE 6
#define PARAM_INSERT_METADATA_BLKSIZE 7
"INSERT INTO metadata(mode, nlink, uid, gid, mtime, size, blksize) VALUES (?, ?, ?, ?, ?, ?, ?)" },
{ STMT_UPDATE_METADATA,
#define PARAM_UPDATE_METADATA_MODE 1
#define PARAM_UPDATE_METADATA_UID 2
#define PARAM_UPDATE_METADATA_GID 3
#define PARAM_UPDATE_METADATA_MTIME 4
#define PARAM_UPDATE_METADATA_SIZE 5
#define PARAM_UPDATE_METADATA_INO 6
"UPDATE metadata SET mode=?, uid=?, gid=?, mtime=?, size=? WHERE ino=?" },
{ STMT_DELETE_METADATA,
#define PARAM_DELETE_METADATA_INO 1
"DELETE FROM metadata WHERE ino = ?" },
{ STMT_INSERT_DIRENTRIES,
#define PARAM_INSERT_DIRENTRIES_DIR_INO 1
#define PARAM_INSERT_DIRENTRIES_ENTRY_NAME 2
#define PARAM_INSERT_DIRENTRIES_ENTRY_INO 3
#define PARAM_INSERT_DIRENTRIES_ENTRY_TYPE 4
"INSERT INTO direntries(dir_ino, entry_name, entry_ino, entry_type) VALUES (?, ?, ?, ?)" },
{ STMT_COUNT_DIRENTRIES,
#define PARAM_COUNT_DIRENTRIES_DIR_INO 1
#define COL_COUNT_DIRENTRIES_COUNT 0
"SELECT count(entry_name) AS count FROM direntries WHERE dir_ino = ?" },
{ STMT_DELETE_DIRENTRIES,
#define PARAM_DELETE_DIRENTRIES_DIR_INO 1
"DELETE FROM direntries WHERE dir_ino = ?" },
{ STMT_DELETE_DIRENTRIES_BY_NAME,
#define PARAM_DELETE_DIRENTRIES_BY_NAME_DIR_INO 1
#define PARAM_DELETE_DIRENTRIES_BY_NAME_ENTRY_NAME 2
"DELETE FROM direntries WHERE dir_ino = ? AND entry_name = ?" },
{ STMT_REPARENT_DIRECTORY,
#define PARAM_REPARENT_DIRECTORY_NEW_PARENT_INO 1
#define PARAM_REPARENT_DIRECTORY_CHILD_INO 2
"UPDATE direntries SET entry_ino = ? WHERE dir_ino = ? AND entry_name = ''" },
{ STMT_READ_DIRENTRIES,
#define PARAM_READ_DIRENTRIES_DIR_INO 1
#define COL_READ_DIRENTRIES_ENTRY_NAME 0
#define COL_READ_DIRENTRIES_ENTRY_INO 1
#define COL_READ_DIRENTRIES_ENTRY_TYPE 2
#define SELECT_DIRENTRIES "SELECT entry_name, entry_ino, entry_type FROM direntries"
#define ORDER_DIRENTRIES "ORDER BY entry_name"
SELECT_DIRENTRIES " WHERE dir_ino = ? " ORDER_DIRENTRIES },
{ STMT_READ_DIRENTRIES_START,
#define PARAM_READ_DIRENTRIES_START_DIR_INO 1
#define PARAM_READ_DIRENTRIES_START_ENTRY_NAME 2
SELECT_DIRENTRIES " WHERE dir_ino = ? AND entry_name >= ? " ORDER_DIRENTRIES },
{ STMT_RENAME,
#define PARAM_RENAME_NEW_DIR_INO 1
#define PARAM_RENAME_NEW_ENTRY_NAME 2
#define PARAM_RENAME_OLD_DIR_INO 3
#define PARAM_RENAME_OLD_ENTRY_NAME 4
"UPDATE direntries SET dir_ino = ?, entry_name = ? WHERE dir_ino = ? AND entry_name = ?" },
{ STMT_READ_FILEDATA,
#define PARAM_READ_FILEDATA_INO 1
#define PARAM_READ_FILEDATA_FROM_IDX 2
#define PARAM_READ_FILEDATA_COUNT 3
#define COL_READ_FILEDATA_IDX 0
#define COL_READ_FILEDATA_DATA 1
"SELECT idx, data FROM filedata WHERE ino = ? AND idx >= ? ORDER BY idx LIMIT ?" },
{ STMT_UPDATE_FILEDATA,
#define PARAM_UPDATE_FILEDATA_INO 1
#define PARAM_UPDATE_FILEDATA_IDX 2
#define PARAM_UPDATE_FILEDATA_DATA 3
"INSERT OR REPLACE INTO filedata(ino, idx, data) VALUES (?, ?, ?)" },
{ STMT_DELETE_FILEDATA,
#define PARAM_DELETE_FILEDATA_INO 1
#define PARAM_DELETE_FILEDATA_FROM_IDX 2
"DELETE FROM filedata WHERE ino = ? AND idx >= ?" },
};
struct sqlfs {
sqlite3 *db;
mode_t umask;
uid_t uid;
gid_t gid;
int blocksize;
sqlite3_stmt *stmt[NUM_STATEMENTS];
sqlite3_stmt *dir_stmt;
bool wal_enabled;
};
enum name_kind { NAME_EMPTY, NAME_DOT, NAME_DOTDOT, NAME_REGULAR };
// NOTE: this doesn't identify names containing a slash (which are invalid too).
static enum name_kind name_kind(const char *name) {
if (name == NULL) return NAME_EMPTY;
if (name[0] == '\0') return NAME_EMPTY;
if (name[0] != '.') return NAME_REGULAR;
if (name[1] == '\0') return NAME_DOT;
if (name[1] != '.') return NAME_REGULAR;
if (name[2] == '\0') return NAME_DOTDOT;
return NAME_REGULAR;
}
static int int_min(int x, int y) {
return x < y ? x : y;
}
static int64_t int64_min(int64_t x, int64_t y) {
return x < y ? x : y;
}
static int64_t int64_max(int64_t x, int64_t y) {
return x > y ? x : y;
}
// Compares two character pointers for equality. Either argument may be NULL.
// The arguments are equal if they are both NULL, or they are both non-NULL and
// they have the same character contents.
static bool strings_equal(const char *s, const char *t) {
return s == t || (s != NULL && t != NULL && strcmp(s, t) == 0);
}
static bool prepare(sqlite3 *db, const char *sql, sqlite3_stmt **stmt) {
if (sqlite3_prepare_v2(db, sql, -1, stmt, NULL) != SQLITE_OK) {
fprintf(stderr, "Failed to prepare statement [%s]: %s\n", sql, sqlite3_errmsg(db));
return false;
}
return true;
}
// Executes an SQL statement that returns no values.
static bool exec_sql(sqlite3 *db, const char *sql) {
sqlite3_stmt *stmt = NULL;
if (!prepare(db, sql, &stmt)) {
return false;
}
int status = sqlite3_step(stmt);
sqlite3_finalize(stmt);
if (status == SQLITE_DONE) {
return true;
}
DLOG("%s(sql=[%s]) status=%d\n", __func__, sql, status);
return false;
}
// Executes a PRAGMA sql statement which is expected to return a value.
//
// (For PRAGMA statements that don't return a value, use exec_sql() instead.)
//
// Returns true if the statement succeeded and returned exactly one row where
// the first column has a string value equal to `expected` (which may be NULL,
// in which case the received value should also be NULL).
static bool exec_pragma(sqlite3 *db, const char *sql, const char *expected) {
sqlite3_stmt *stmt = NULL;
if (!prepare(db, sql, &stmt)) {
return false;
}
bool success = false;
if (sqlite3_step(stmt) != SQLITE_ROW) {
DLOG("%s(sql=[%s]) failed (PRAGMA not supported by this version?)\n", __func__, sql);
} else {
const char *received = (const char*)sqlite3_column_text(stmt, 0);
if (!strings_equal(expected, received)) {
DLOG("%s(sql=[%s]) expected [%s] != received [%s]\n", __func__, sql,
expected != NULL ? expected : "<null>",
received != NULL ? received : "<null>");
} else if (sqlite3_step(stmt) != SQLITE_DONE) {
DLOG("%s(sql=[%s]) failed\n", __func__, sql);
} else {
success = true;
}
}
sqlite3_finalize(stmt);
return success;
}
static void sql_savepoint(struct sqlfs *sqlfs) {
sqlite3_stmt * const stmt = sqlfs->stmt[STMT_SAVEPOINT];
CHECK(sqlite3_step(stmt) == SQLITE_DONE);
sqlite3_reset(stmt);
}
static void sql_release_savepoint(struct sqlfs *sqlfs) {
sqlite3_stmt * const stmt = sqlfs->stmt[STMT_RELEASE_SAVEPOINT];
CHECK(sqlite3_step(stmt) == SQLITE_DONE);
sqlite3_reset(stmt);
}
static void sql_rollback_to_savepoint(struct sqlfs *sqlfs) {
sqlite3_stmt * const stmt = sqlfs->stmt[STMT_ROLLBACK_TO_SAVEPOINT];
CHECK(sqlite3_step(stmt) == SQLITE_DONE);
sqlite3_reset(stmt);
}
int sqlfs_get_sqlcipher_version(struct sqlcipher_version *result) {
bool success = false;
sqlite3 *db;
CHECK(sqlite3_open(":memory:", &db) == SQLITE_OK);
sqlite3_stmt *stmt = NULL;
CHECK(prepare(db, "PRAGMA cipher_version", &stmt));
if (sqlite3_step(stmt) == SQLITE_ROW) {
const char *text = (const char*)sqlite3_column_text(stmt, 0);
struct sqlcipher_version version = {0, 0, 0};
if (text != NULL && sscanf(text, "%d.%d.%d", &version.major, &version.minor, &version.patch) == 3) {
*result = version;
success = true;
}
CHECK(sqlite3_step(stmt) == SQLITE_DONE);
}
sqlite3_finalize(stmt);
CHECK(sqlite3_close(db) == SQLITE_OK);
return success ? 0 : EIO;
}
// Retrieves the runtime version number of the SQLCipher library and returns
// true if the major version is at least MIN_CIPHER_COMPAT. Otherwise, it
// prints an error message and returns false.
static bool get_supported_sqlcipher_version(struct sqlcipher_version *result) {
if (sqlfs_get_sqlcipher_version(result) != 0) {
return false;
}
if (result->major < MIN_CIPHER_COMPAT) {
fprintf(stderr, "Unsupported SQLCipher version: %d.%d.%d (minimum: %d.0.0)\n",
result->major, result->minor, result->patch, MIN_CIPHER_COMPAT);
return false;
}
return true;
}
static int get_user_version_with_status(sqlite3 *db, int64_t *result) {
sqlite3_stmt *stmt = NULL;
CHECK(prepare(db, "PRAGMA user_version", &stmt));
int status = sqlite3_step(stmt);
if (status == SQLITE_ROW) {
*result = sqlite3_column_int64(stmt, 0);
CHECK(sqlite3_step(stmt) == SQLITE_DONE);
}
sqlite3_finalize(stmt);
return status;
}
static int64_t get_user_version(sqlite3 *db) {
int64_t result;
return get_user_version_with_status(db, &result) == SQLITE_ROW ? result : -1;
}
static struct timespec current_timespec() {
struct timespec tp;
CHECK(clock_gettime(CLOCK_REALTIME, &tp) == 0);
return tp;
}
// Converts a timespec structure to a 64-bit integer timestamp in nanoseconds.
// The result is clamped into the range [INT64_MIN:INT64_MAX] if necessary.
// This range allows dates between the year 1823 and 2116 to be represented.d
static int64_t timespec_to_nanos(const struct timespec *tp) {
if (tp->tv_sec >= 0) {
if (tp->tv_sec > INT64_MAX/NANOS_PER_SECOND ||
INT64_MAX - (int64_t)tp->tv_sec * NANOS_PER_SECOND < tp->tv_nsec) {
return INT64_MAX;
}
} else { // tp->tv_sec < 0
if (tp->tv_sec < INT64_MIN/NANOS_PER_SECOND ||
INT64_MIN - (int64_t)tp->tv_sec * NANOS_PER_SECOND > tp->tv_nsec) {
return INT64_MIN;
}
}
return (int64_t)tp->tv_sec * NANOS_PER_SECOND + tp->tv_nsec;
}
static int64_t current_time_nanos() {
struct timespec tp = current_timespec();
return timespec_to_nanos(&tp);
}
static struct timespec nanos_to_timespec(int64_t nanos) {
int64_t sec = nanos / NANOS_PER_SECOND;
int64_t nsec = nanos % NANOS_PER_SECOND;
if (nsec < 0) {
sec -= 1;
nsec += NANOS_PER_SECOND;
}
struct timespec res = {
.tv_sec = sec,
.tv_nsec = nsec };
return res;
}
// Creates the root directory in an empty, newly created filesystem.
//
// This is basically a special-case version of sqlfs_mkdir that doesn't use
// prepared statements so it can be called during initialization, before the
// schema has been committed.
static bool create_root_directory(sqlite3 *db, mode_t umask, uid_t uid, gid_t gid) {
const mode_t mode = (0777 &~ umask) | S_IFDIR;
{
sqlite3_stmt *stmt = NULL;
CHECK(prepare(db, "INSERT INTO metadata(ino, mode, nlink, uid, gid, mtime) VALUES (?, ?, ?, ?, ?, ?)", &stmt));
CHECK(sqlite3_bind_int64(stmt, 1, SQLFS_INO_ROOT) == SQLITE_OK);
CHECK(sqlite3_bind_int64(stmt, 2, mode) == SQLITE_OK);
CHECK(sqlite3_bind_int64(stmt, 3, 1) == SQLITE_OK); // nlink
CHECK(sqlite3_bind_int64(stmt, 4, uid) == SQLITE_OK);
CHECK(sqlite3_bind_int64(stmt, 5, gid) == SQLITE_OK);
CHECK(sqlite3_bind_int64(stmt, 6, current_time_nanos()) == SQLITE_OK);
int status = sqlite3_step(stmt);
sqlite3_finalize(stmt);
if (status != SQLITE_DONE) {
return false;
}
}
{
sqlite3_stmt *stmt = NULL;
CHECK(prepare(db, "INSERT INTO direntries(dir_ino, entry_name, entry_ino, entry_type) VALUES (?, ?, ?, ?)", &stmt));
CHECK(sqlite3_bind_int64(stmt, 1, SQLFS_INO_ROOT) == SQLITE_OK);
CHECK(sqlite3_bind_text(stmt, 2, "", 0, SQLITE_STATIC) == SQLITE_OK);
CHECK(sqlite3_bind_int64(stmt, 3, SQLFS_INO_ROOT) == SQLITE_OK);
CHECK(sqlite3_bind_int64(stmt, 4, mode >> 12) == SQLITE_OK);
int status = sqlite3_step(stmt);
sqlite3_finalize(stmt);
if (status != SQLITE_DONE) {
return false;
}
}
return true;
}
static void fill_stat(sqlite3_stmt *stmt, struct stat *stat, int default_blocksize) {
memset(stat, 0, sizeof(*stat));
stat->st_ino = sqlite3_column_int64(stmt, COL_STAT_INO);
const mode_t mode = sqlite3_column_int64(stmt, COL_STAT_MODE);
stat->st_mode = mode;
stat->st_nlink = sqlite3_column_int64(stmt, COL_STAT_NLINK) + S_ISDIR(mode);
stat->st_uid = sqlite3_column_int64(stmt, COL_STAT_UID);
stat->st_gid = sqlite3_column_int64(stmt, COL_STAT_GID);
// stat->st_rdev is kept zero.
const int64_t size = sqlite3_column_int64(stmt, COL_STAT_SIZE);
stat->st_size = size;
// Blocksize for filesystem I/O
stat->st_blksize = sqlite3_column_type(stmt, COL_STAT_BLKSIZE) == SQLITE_NULL
? default_blocksize : sqlite3_column_int64(stmt, COL_STAT_BLKSIZE);
// Size in 512 byte blocks. Unrelated to blocksize above!
stat->st_blocks = (size + 511) >> 9;
// atim/mtim/ctim are all set to the last modification timestamp.
stat->st_atim = stat->st_mtim = stat->st_ctim =
nanos_to_timespec(sqlite3_column_int64(stmt, COL_STAT_MTIME));
}
static int finish_stat_query(sqlite3_stmt *stmt, struct stat *stat, int default_blocksize) {
int err = -1;
int status = sqlite3_step(stmt);
if (status == SQLITE_DONE) {
err = ENOENT;
} else if (status == SQLITE_ROW) {
fill_stat(stmt, stat, default_blocksize);
CHECK(sqlite3_step(stmt) == SQLITE_DONE);
err = 0;
} else {
DLOG("%s() status=%d\n", __func__, status);
err = EIO;
}
sqlite3_reset(stmt);
sqlite3_clear_bindings(stmt);
CHECK(err >= 0);
return err;
}
static int sql_stat_entry(struct sqlfs *sqlfs, ino_t dir_ino, const char *entry_name, struct stat *stat) {
sqlite3_stmt *stmt = sqlfs->stmt[STMT_STAT_ENTRY];
CHECK(sqlite3_bind_int64(stmt, PARAM_STAT_ENTRY_DIR_INO, dir_ino) == SQLITE_OK);
CHECK(sqlite3_bind_text(stmt, PARAM_STAT_ENTRY_ENTRY_NAME, entry_name, -1, SQLITE_STATIC) == SQLITE_OK);
return finish_stat_query(stmt, stat, sqlfs->blocksize);
}
// Allocates an inode number for a new file/directory with the given mode and
// link count. On success, *stat contains the generated attributes. In
// particular, the generated inode number is returned in stat->st_ino.
//
// Inode numbers may be re-used over the lifetime of the filesystem! (For
// example, if file A with inode 42 is deleted, it is possibly that file B is
// later created with the same inode number 42.)
//
// Returns 0 on success, or EIO if the database operation failed.
static int sql_insert_metadata(struct sqlfs *sqlfs, mode_t mode, nlink_t nlink, struct stat *stat) {
memset(stat, 0, sizeof(*stat));
stat->st_mode = mode;
stat->st_nlink = nlink + S_ISDIR(mode);
stat->st_uid = sqlfs->uid;
stat->st_gid = sqlfs->gid;
stat->st_blksize = sqlfs->blocksize;
stat->st_mtim = stat->st_ctim = stat->st_atim = current_timespec();
sqlite3_stmt *stmt = sqlfs->stmt[STMT_INSERT_METADATA];
CHECK(sqlite3_bind_int64(stmt, PARAM_INSERT_METADATA_MODE, mode) == SQLITE_OK);
CHECK(sqlite3_bind_int64(stmt, PARAM_INSERT_METADATA_NLINK, nlink) == SQLITE_OK);
CHECK(sqlite3_bind_int64(stmt, PARAM_INSERT_METADATA_UID, sqlfs->uid) == SQLITE_OK);
CHECK(sqlite3_bind_int64(stmt, PARAM_INSERT_METADATA_GID, sqlfs->gid) == SQLITE_OK);
CHECK(sqlite3_bind_int64(stmt, PARAM_INSERT_METADATA_MTIME, timespec_to_nanos(&stat->st_mtim)) == SQLITE_OK);
if (!S_ISDIR(mode)) {
CHECK(sqlite3_bind_int64(stmt, PARAM_INSERT_METADATA_SIZE, 0) == SQLITE_OK);
CHECK(sqlite3_bind_int64(stmt, PARAM_INSERT_METADATA_BLKSIZE, sqlfs->blocksize) == SQLITE_OK);
}
int status = sqlite3_step(stmt);
if (status != SQLITE_DONE) {
DLOG("%s() status=%d\n", __func__, status);
} else {
stat->st_ino = sqlite3_last_insert_rowid(sqlfs->db);
CHECK(stat->st_ino > 0);
}
sqlite3_reset(stmt);
sqlite3_clear_bindings(stmt);
return stat->st_ino > 0 ? 0 : EIO;
}
// Update the metadata for a file/directory identified by its inode number,
// which is passed in stat->st_ino.
//
// Only the following fields are updated: st_mode (permission bits only),
// st_uid, st_gid, st_mtime, st_size.
//
// File size can only be changed for files (not directories). The caller must
// make sure that the filedata table is updated separately.
//
// Returns:
// 0 on success
// ENOENT if no metadata entry exists with the given inode number
// EIO if writing to the database failed
static int sql_update_metadata(struct sqlfs *sqlfs, const struct stat *stat) {
sqlite3_stmt *stmt = sqlfs->stmt[STMT_UPDATE_METADATA];
CHECK(sqlite3_bind_int64(stmt, PARAM_UPDATE_METADATA_INO, stat->st_ino) == SQLITE_OK);
CHECK(sqlite3_bind_int64(stmt, PARAM_UPDATE_METADATA_MODE, stat->st_mode) == SQLITE_OK);
CHECK(sqlite3_bind_int64(stmt, PARAM_UPDATE_METADATA_UID, stat->st_uid) == SQLITE_OK);
CHECK(sqlite3_bind_int64(stmt, PARAM_UPDATE_METADATA_GID, stat->st_gid) == SQLITE_OK);
CHECK(sqlite3_bind_int64(stmt, PARAM_UPDATE_METADATA_MTIME, timespec_to_nanos(&stat->st_mtim)) == SQLITE_OK);
if (!S_ISDIR(stat->st_mode)) {
CHECK(sqlite3_bind_int64(stmt, PARAM_UPDATE_METADATA_SIZE, stat->st_size) == SQLITE_OK);
}
int err = 0;
int status = sqlite3_step(stmt);
if (status != SQLITE_DONE) {
DLOG("%s() status=%d\n", __func__, status);
err = EIO;
} else if (sqlite3_changes(sqlfs->db) == 0) {
err = ENOENT;
}
sqlite3_reset(stmt);
sqlite3_clear_bindings(stmt);
return err;
}
// Deletes the metadata for a file/directory. Caller must make sure the contents
// of the file/directory are deleted separately!
//
// Returns 0 on success, or EIO if the database operation fails.
static int sql_delete_metadata(struct sqlfs *sqlfs, ino_t ino) {
sqlite3_stmt *stmt = sqlfs->stmt[STMT_DELETE_METADATA];
CHECK(sqlite3_bind_int64(stmt, PARAM_DELETE_METADATA_INO, ino) == SQLITE_OK);
int status = sqlite3_step(stmt);
sqlite3_reset(stmt);
sqlite3_clear_bindings(stmt);
return status == SQLITE_DONE ? 0 : EIO;
}
// Updates the hardlink count for the given inode number, by adding add_links
// to the current link count. This function doesn't check that the new value is
// in range!
//
// Returns:
// 0 on success,
// ENOENT if the ino does not exist
// EIO for other SQLite errors
static int sql_update_nlink(struct sqlfs *sqlfs, ino_t ino, int64_t add_links) {
sqlite3_stmt *stmt = sqlfs->stmt[STMT_UPDATE_NLINK];
CHECK(sqlite3_bind_int64(stmt, PARAM_UPDATE_NLINK_ADD_LINKS, add_links) == SQLITE_OK);
CHECK(sqlite3_bind_int64(stmt, PARAM_UPDATE_NLINK_INO, ino) == SQLITE_OK);
int err = -1;
int status = sqlite3_step(stmt);
if (status != SQLITE_DONE) {
DLOG("%s(ino=%lld, add_links=%lld) status=%d\n",
__func__, (long long) ino, (long long) add_links, status);
err = EIO;
goto finish;
}
int changes = sqlite3_changes(sqlfs->db);
if (changes == 0) {
err = ENOENT;
goto finish;
}
CHECK(changes == 1);
err = 0;
finish:
sqlite3_reset(stmt);
sqlite3_clear_bindings(stmt);
CHECK(err >= 0);
return err;
}
// Increments the hardlink count for the given inode number.
// See sql_update_nlink() for return values.
static int sql_inc_nlink(struct sqlfs *sqlfs, ino_t ino) {
return sql_update_nlink(sqlfs, ino, +1);
}
// Decrements the hardlink count for the given inode number.
// See sql_update_nlink() for return values.
static int sql_dec_nlink(struct sqlfs *sqlfs, ino_t ino) {
return sql_update_nlink(sqlfs, ino, -1);
}
// Retrieves an entry from the `direntry` table.
//
// Returns:
// 0 on success
// ENOENT if the entry is not found (including if dir_ino didn't exist!)
// EIO on SQLite error
static int sql_lookup(struct sqlfs *sqlfs, ino_t dir_ino, const char *entry_name,
ino_t *child_ino, mode_t *child_mode) {
sqlite3_stmt *stmt = sqlfs->stmt[STMT_LOOKUP];
CHECK(sqlite3_bind_int64(stmt, PARAM_LOOKUP_DIR_INO, dir_ino) == SQLITE_OK);
CHECK(sqlite3_bind_text(stmt, PARAM_LOOKUP_ENTRY_NAME, entry_name, -1, SQLITE_STATIC) == SQLITE_OK);
int status = sqlite3_step(stmt);
int err = -1;
if (status == SQLITE_ROW) {
*child_ino = sqlite3_column_int64(stmt, COL_LOOKUP_ENTRY_INO);
*child_mode = sqlite3_column_int64(stmt, COL_LOOKUP_ENTRY_TYPE) << 12;
err = 0;
} else if (status == SQLITE_DONE) {
err = ENOENT;
} else {
DLOG("%s(dir_ino=%lld, name=[%s]) status=%d\n",
__func__, (long long)dir_ino, entry_name, status);
err = EIO;
}
sqlite3_reset(stmt);
sqlite3_clear_bindings(stmt);
CHECK(err >= 0);
return err;
}
// Insert an entry into the direntries table. Only the file type bits of mode are stored!
// Entry name must not be "." or "..", but it may be the empty string, which corresponds
// with "..".
//
// Returns:
// 0 on success
// EEXIST if the named entry already exists
// EIO if another SQLite error occurred
static int sql_insert_direntries(struct sqlfs *sqlfs, ino_t dir_ino, const char *entry_name, ino_t entry_ino, mode_t entry_mode) {
sqlite3_stmt *stmt = sqlfs->stmt[STMT_INSERT_DIRENTRIES];
CHECK(sqlite3_bind_int64(stmt, PARAM_INSERT_DIRENTRIES_DIR_INO, dir_ino) == SQLITE_OK);
CHECK(sqlite3_bind_text(stmt, PARAM_INSERT_DIRENTRIES_ENTRY_NAME, entry_name, -1, SQLITE_STATIC) == SQLITE_OK);
CHECK(sqlite3_bind_int64(stmt, PARAM_INSERT_DIRENTRIES_ENTRY_INO, entry_ino) == SQLITE_OK);
CHECK(sqlite3_bind_int64(stmt, PARAM_INSERT_DIRENTRIES_ENTRY_TYPE, entry_mode >> 12) == SQLITE_OK);
int status = sqlite3_step(stmt);
sqlite3_reset(stmt);
sqlite3_clear_bindings(stmt);
switch (status) {
case SQLITE_DONE:
return 0;
case SQLITE_CONSTRAINT:
return EEXIST;
default:
DLOG("%s(dir_ino=%lld, entry_name=%s, entry_ino=%lld, entry_mode=0%o) status=%d\n",
__func__, (long long)dir_ino, entry_name, (long long)entry_ino, entry_mode, status);
return EIO;
}
}
// Returns a count of the number of directory entries for the directory with
// inode number `dir_ino`, including the empty entry (corresponding to "..").
// That means the count is 1 for an empty directory, or 0 for non-existent
// directories (including files, which aren't directories).
static int64_t sql_count_direntries(struct sqlfs *sqlfs, ino_t dir_ino) {
sqlite3_stmt *stmt = sqlfs->stmt[STMT_COUNT_DIRENTRIES];
CHECK(sqlite3_bind_int64(stmt, PARAM_COUNT_DIRENTRIES_DIR_INO, dir_ino) == SQLITE_OK);
CHECK(sqlite3_step(stmt) == SQLITE_ROW);
const int64_t result = sqlite3_column_int64(stmt, COL_COUNT_DIRENTRIES_COUNT);
CHECK(sqlite3_step(stmt) == SQLITE_DONE);
sqlite3_reset(stmt);
sqlite3_clear_bindings(stmt);
return result;
}
// Deletes the directory entry with the given name.
//
// This doesn't delete files/directories recursively. The caller must make sure
// that the file/directory being deleted is still linked elsewhere, or delete it
// separately.
//
// Returns 0 on success, or EIO if the database operation fails.
static int sql_delete_direntry(struct sqlfs *sqlfs, ino_t dir_ino, const char *entry_name) {
sqlite3_stmt *stmt = sqlfs->stmt[STMT_DELETE_DIRENTRIES_BY_NAME];
CHECK(sqlite3_bind_int64(stmt, PARAM_DELETE_DIRENTRIES_BY_NAME_DIR_INO, dir_ino) == SQLITE_OK);
CHECK(sqlite3_bind_text(stmt, PARAM_DELETE_DIRENTRIES_BY_NAME_ENTRY_NAME, entry_name, -1, SQLITE_STATIC) == SQLITE_OK);
int status = sqlite3_step(stmt);
sqlite3_reset(stmt);
sqlite3_clear_bindings(stmt);
return status == SQLITE_DONE ? 0 : EIO;
}
// Changes the parent directory reference for the child directory with the given
// inode number.
//
// The caller must ensure that child_ino is an existing directory, and that no
// cycles are introduced by the reparenting operation. This function only
// updates the direntries table. It is the caller's responsibility to update the
// link count for the directories.
//
// Returns 0 on succes, or EIO if a database operation fails.
static int sql_reparent_directory(struct sqlfs *sqlfs, ino_t child_ino, ino_t new_parent_ino) {
sqlite3_stmt *stmt = sqlfs->stmt[STMT_REPARENT_DIRECTORY];
CHECK(sqlite3_bind_int64(stmt, PARAM_REPARENT_DIRECTORY_NEW_PARENT_INO, new_parent_ino) == SQLITE_OK);
CHECK(sqlite3_bind_int64(stmt, PARAM_REPARENT_DIRECTORY_CHILD_INO, child_ino) == SQLITE_OK);
int status = sqlite3_step(stmt);
sqlite3_reset(stmt);
sqlite3_clear_bindings(stmt);
return status == SQLITE_DONE && sqlite3_changes(sqlfs->db) == 1 ? 0 : EIO;
}
// Deletes all entries in the given directory. This includes the empty entry
// (corresponding to "..") so afterwards, the directory is in an invalid state,
// and its metadata should be removed separately.
//
// This doesn't delete files/directories recursively. The caller must make sure
// that the directory is empty before deleting its entries.
//
// Returns 0 on success, or EIO if the database operation fails.
static int sql_delete_direntries(struct sqlfs *sqlfs, ino_t dir_ino) {
sqlite3_stmt *stmt = sqlfs->stmt[STMT_DELETE_DIRENTRIES];
CHECK(sqlite3_bind_int64(stmt, PARAM_DELETE_DIRENTRIES_DIR_INO, dir_ino) == SQLITE_OK);
int status = sqlite3_step(stmt);
sqlite3_reset(stmt);
sqlite3_clear_bindings(stmt);
return status == SQLITE_DONE ? 0 : EIO;
}
// Renames a directory entry and/or moves it a different directory.
//
// The caller must ensure that:
//
// - old_dir_ino and new_dir_ino refer to directories
// - the entry identified by (old_dir_ino, old_entry_name) exists
// - the entry identified by (new_dir_ino, new_entry_name) does not exist
// - no cycles are introduced by moving the old entry into the new directory
//
// Returns 0 on success, or EIO if the database operation fails (possibly
// because one of the constraints outlined above was violated).
static int sql_rename(struct sqlfs *sqlfs,
ino_t old_dir_ino, const char *old_entry_name,
ino_t new_dir_ino, const char *new_entry_name) {
sqlite3_stmt *stmt = sqlfs->stmt[STMT_RENAME];
CHECK(sqlite3_bind_int64(stmt, PARAM_RENAME_NEW_DIR_INO, new_dir_ino) == SQLITE_OK);
CHECK(sqlite3_bind_text(stmt, PARAM_RENAME_NEW_ENTRY_NAME, new_entry_name, -1, SQLITE_STATIC) == SQLITE_OK);
CHECK(sqlite3_bind_int64(stmt, PARAM_RENAME_OLD_DIR_INO, old_dir_ino) == SQLITE_OK);
CHECK(sqlite3_bind_text(stmt, PARAM_RENAME_OLD_ENTRY_NAME, old_entry_name, -1, SQLITE_STATIC) == SQLITE_OK);
int status = sqlite3_step(stmt);
sqlite3_reset(stmt);
sqlite3_clear_bindings(stmt);
return status == SQLITE_DONE && sqlite3_changes(sqlfs->db) == 1 ? 0 : EIO;
}
// Reads filedata bytes from the given file into a buffer.
//
// If there is not enough file data to fill the buffer, this function will fail!
// It is assumed that the caller knows exactly how large the file is, and adjust
// its read calls accordingly.
//
// `blocksize` must be a positive integer: the blocksize of the file identified
// by `ino`. `offset` and `size` must be nonnegative integers. `buf` must point
// to a buffer at least `size` bytes long.
//
// Returns 0 on success, or EIO if the database operation fails.
static int sql_read_filedata(struct sqlfs *sqlfs, ino_t ino, int64_t blocksize, int64_t offset, int64_t size, char *buf) {
CHECK(blocksize > 0);
CHECK(offset >= 0);
CHECK(size >= 0);
if (size == 0) {
return 0;
}
int err = 0;
// Range of blocks to read: from block_idx_begin (inclusive) to block_idx_end (exclusive).
int64_t block_idx_begin = offset/blocksize;
int64_t block_idx_end = (offset + size + blocksize - 1)/blocksize;
sqlite3_stmt *stmt = sqlfs->stmt[STMT_READ_FILEDATA];
CHECK(sqlite3_bind_int64(stmt, PARAM_READ_FILEDATA_INO, ino) == SQLITE_OK);
CHECK(sqlite3_bind_int64(stmt, PARAM_READ_FILEDATA_FROM_IDX, block_idx_begin) == SQLITE_OK);
CHECK(sqlite3_bind_int64(stmt, PARAM_READ_FILEDATA_COUNT, block_idx_end - block_idx_begin) == SQLITE_OK);
// Fill buffer by reading a sequence of chunks. Each chunk starts at a block
// boundary and is at most `blocksize` bytes long (but the last chunk may be
// shorter than that).
for (int64_t i = block_idx_begin; i < block_idx_end; ++i) {
int64_t chunk_offset = i*blocksize;
int64_t chunk_size = int64_min(offset + size - chunk_offset, blocksize);
int status = sqlite3_step(stmt);
if (status != SQLITE_ROW) {
DLOG("%s() status=%d\n", __func__, status);
err = EIO;
goto finish;
}
int64_t block_idx = sqlite3_column_int64(stmt, COL_READ_FILEDATA_IDX);
if (block_idx != i) {
DLOG("%s() ino=%lld incorrect block index! expected: %lld received: %lld",
__func__, (long long)ino, (long long)i, (long long)block_idx);
err = EIO;
goto finish;
}
const char *data_ptr = sqlite3_column_blob(stmt, COL_READ_FILEDATA_DATA);
CHECK(data_ptr != NULL);
int64_t data_size = sqlite3_column_bytes(stmt, COL_READ_FILEDATA_DATA);
if (data_size < chunk_size) {
DLOG("%s() ino=%lld idx=%lld incorrect block size! expected: %lld received: %lld",
__func__, (long long)ino, (long long)i, (long long)chunk_size, (long long)data_size);
err = EIO;
goto finish;
}
if (chunk_offset < offset) {
// First chunk. Only copy the part overlapping the range to be read.
memcpy(buf, data_ptr + (offset - chunk_offset), chunk_size - (offset - chunk_offset));
} else {
memcpy(buf + (chunk_offset - offset), data_ptr, chunk_size);
}
}
CHECK(sqlite3_step(stmt) == SQLITE_DONE);
finish:
sqlite3_reset(stmt);
sqlite3_clear_bindings(stmt);
return err;
}
// Writes one block of data to the filedata table.
//
// Returns 0 on success, or EIO if the database operation fails.
static int sql_update_filedata(struct sqlfs *sqlfs, ino_t ino, int64_t block_idx, const char *block_data, size_t block_size) {
sqlite3_stmt *stmt = sqlfs->stmt[STMT_UPDATE_FILEDATA];
CHECK(sqlite3_bind_int64(stmt, PARAM_UPDATE_FILEDATA_INO, ino) == SQLITE_OK);
CHECK(sqlite3_bind_int64(stmt, PARAM_UPDATE_FILEDATA_IDX, block_idx) == SQLITE_OK);
CHECK(sqlite3_bind_blob64(stmt, PARAM_UPDATE_FILEDATA_DATA, block_data, block_size, SQLITE_STATIC) == SQLITE_OK);
int status = sqlite3_step(stmt);
sqlite3_reset(stmt);
sqlite3_clear_bindings(stmt);
return status == SQLITE_DONE ? 0 : EIO;
}
// Deletes the filedata blocks for the file with the given inode number,
// starting from the block with index from_idx. (Consequently, if from_idx <= 0,
// then all filedata blocks are deleted.) The caller must update/delete the file
// metadata separately.
//
// Returns 0 on success, or EIO if the database operation fails.
static int sql_delete_filedata(struct sqlfs *sqlfs, ino_t ino, int64_t from_idx) {
sqlite3_stmt *stmt = sqlfs->stmt[STMT_DELETE_FILEDATA];
CHECK(sqlite3_bind_int64(stmt, PARAM_DELETE_FILEDATA_INO, ino) == SQLITE_OK);
CHECK(sqlite3_bind_int64(stmt, PARAM_DELETE_FILEDATA_FROM_IDX, from_idx) == SQLITE_OK);
int status = sqlite3_step(stmt);
sqlite3_reset(stmt);
sqlite3_clear_bindings(stmt);
return status == SQLITE_DONE ? 0 : EIO;
}
// Enable exclusive locking mode on the database. This has two effects:
// 1. Prevents others from accessing the same filesystem.
// 2. Allows WAL journaling without using shared memory files.
static bool enable_exclusive(sqlite3 *db) {
return exec_pragma(db, "PRAGMA locking_mode = exclusive", "exclusive");
}
// Enable secure delete on the database. This ensures that deleted data is
// overwritten with zeroes, which prevents recovering deleted data from a later
// version of the database, even if the key is known.
static bool enable_secure_delete(sqlite3 *db) {
return exec_pragma(db, "PRAGMA secure_delete = true", "1");
}
// Enable WAL journaling mode for higher write performance.
// More information: https://www.sqlite.org/wal.html
static bool enable_wal(sqlite3 *db) {
return
// Lowest level of synchronicity that we can get away with without losing
// consistency. (Note that we lose durability, but that's probably okay.)
exec_sql(db, "PRAGMA synchronous = normal") &&
// Verify result of previous statement.
exec_pragma(db, "PRAGMA synchronous", "1" /*normal*/) &&
// Enable write-ahead logging journaling mode.
exec_pragma(db, "PRAGMA journal_mode = wal", "wal");
}
// Reset journaling mode to allow the database to be opened in read-only mode
// (assuming it was cleanly closed and doesn't need recovery at start-up).
static bool disable_wal(sqlite3 *db) {
return
exec_sql(db, "PRAGMA synchronous = full") &&
exec_pragma(db, "PRAGMA synchronous", "2" /*full*/) &&
exec_pragma(db, "PRAGMA journal_mode = delete", "delete");
}
// Sets the encryption parameters (password and cipher page size) of the
// database. This must be done immediately after opening the database.
// If password == NULL, this function does nothing but returns true.
static bool set_password(sqlite3 *db, const char *password, int kdf_iter, int cipher_compatibility) {
if (password == NULL) {
return true;
}
if (kdf_iter < 0 || cipher_compatibility < MIN_CIPHER_COMPAT) {
return false;
}
if (sqlite3_key(db, password, strlen(password)) != SQLITE_OK) {
return false;
}
// Select parameters from SQLCipher version 3 for backward compatibilty
// when using SQLCipher version 4.
//
// Practically, this has the effect of selecting the following parameters:
//
// PRAGMA version 3 default version 4 default
// ------------------------ ------------------ --------------------
// cipher_page_size 1024 4096
// kdf_iter 64000 256000
// cipher_hmac_algorithm HMAC_SHA1 HMAC_SHA256
// cipher_kdf_algorithm PBKDF2_HMAC_SHA1 PBKDF2_HMAC_SHA512
//
// Note that the cipher_compatibility PRAGMA is supported since version 4
// only. Version 3 will ignore the PRAGMA, but use the correct defaults.
// Version 2 and below are not supported.
char buf[64];
snprintf(buf, sizeof(buf), "PRAGMA cipher_compatibility = %d", cipher_compatibility);
if (!exec_sql(db, buf)) {
return false;
}
// We support overriding kdf_iter to speed up tests only!
if (kdf_iter > 0) {
snprintf(buf, sizeof(buf), "PRAGMA kdf_iter = %d", kdf_iter);
if (!exec_sql(db, buf)) {
return false;
}
}
return true;
}
static bool validate_options(const struct sqlfs_options *options) {
if (options == NULL) {