1 // Copyright 2019 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "sql/sandboxed_vfs.h"
13 #include "base/check_op.h"
14 #include "base/files/file.h"
15 #include "base/no_destructor.h"
16 #include "base/notreached.h"
17 #include "base/threading/platform_thread.h"
18 #include "build/build_config.h"
19 #include "sql/initialization.h"
20 #include "sql/sandboxed_vfs_file.h"
21 #include "third_party/sqlite/sqlite3.h"
27 // Extracts the SandboxedVfs* stashed in a SQLite VFS structure.
28 SandboxedVfs& SandboxedVfsFromSqliteVfs(sqlite3_vfs& vfs) {
29 return *reinterpret_cast<SandboxedVfs*>(vfs.pAppData);
32 int SandboxedVfsOpen(sqlite3_vfs* vfs,
33 const char* full_path,
34 sqlite3_file* result_file,
37 return SandboxedVfsFromSqliteVfs(*vfs).Open(full_path, *result_file,
38 requested_flags, granted_flags);
40 int SandboxedVfsDelete(sqlite3_vfs* vfs, const char* full_path, int sync_dir) {
41 return SandboxedVfsFromSqliteVfs(*vfs).Delete(full_path, sync_dir);
43 int SandboxedVfsAccess(sqlite3_vfs* vfs,
44 const char* full_path,
47 return SandboxedVfsFromSqliteVfs(*vfs).Access(full_path, flags, *result);
49 int SandboxedVfsFullPathname(sqlite3_vfs* vfs,
50 const char* file_path,
53 return SandboxedVfsFromSqliteVfs(*vfs).FullPathname(file_path, result_size,
56 int SandboxedVfsRandomness(sqlite3_vfs* vfs, int result_size, char* result) {
57 return SandboxedVfsFromSqliteVfs(*vfs).Randomness(result_size, result);
59 int SandboxedVfsSleep(sqlite3_vfs* vfs, int microseconds) {
60 return SandboxedVfsFromSqliteVfs(*vfs).Sleep(microseconds);
62 int SandboxedVfsGetLastError(sqlite3_vfs* vfs,
65 return SandboxedVfsFromSqliteVfs(*vfs).GetLastError(message_size, message);
67 int SandboxedVfsCurrentTimeInt64(sqlite3_vfs* vfs, sqlite3_int64* result_ms) {
68 return SandboxedVfsFromSqliteVfs(*vfs).CurrentTimeInt64(result_ms);
71 sqlite3_vfs SqliteVfsFor(SandboxedVfs* sandboxed_vfs, const char* name) {
72 DCHECK_EQ(sandboxed_vfs, reinterpret_cast<SandboxedVfs*>(
73 reinterpret_cast<void*>(sandboxed_vfs)))
74 << "This implementation round-trips SandboxedVfs* via void*";
76 // VFS API entry points are listed at https://www.sqlite.org/c3ref/vfs.html
77 static constexpr int kSqliteVfsApiVersion = 3;
79 // Maximum file path size.
80 // TODO(pwnall): Obtain this from //base or some other good place.
81 static constexpr int kSqliteMaxPathSize = 512;
85 sizeof(SandboxedVfsFileSqliteBridge),
89 /*pAppData=*/reinterpret_cast<void*>(sandboxed_vfs),
93 SandboxedVfsFullPathname,
98 SandboxedVfsRandomness,
100 /*xCurrentTime=*/nullptr, // Deprecated in API versions 2 and above.
101 SandboxedVfsGetLastError,
102 SandboxedVfsCurrentTimeInt64,
103 /*xSetSystemCall=*/nullptr,
104 /*xGetSystemCall=*/nullptr,
105 /*xNextSystemCall=*/nullptr,
109 // SQLite measures time according to the Julian calendar.
110 base::Time SqliteEpoch() {
111 constexpr const double kMicroSecondsPerDay = 24 * 60 * 60 * 1000;
112 // The ".5" is intentional -- days in the Julian calendar start at noon.
113 // The offset is in the SQLite source code (os_unix.c) multiplied by 10.
114 constexpr const double kUnixEpochAsJulianDay = 2440587.5;
116 return base::Time::FromJsTime(-kUnixEpochAsJulianDay * kMicroSecondsPerDay);
120 // `full_path_cstr` must be a filename argument passed to the VFS from SQLite.
121 SandboxedVfsFileType VfsFileTypeFromPath(const char* full_path_cstr) {
122 base::StringPiece full_path(full_path_cstr);
124 const char* database_file_cstr = sqlite3_filename_database(full_path_cstr);
125 base::StringPiece database_file(database_file_cstr);
126 if (full_path == database_file)
127 return SandboxedVfsFileType::kDatabase;
129 const char* journal_file_cstr = sqlite3_filename_journal(full_path_cstr);
130 base::StringPiece journal_file(journal_file_cstr);
131 if (full_path == journal_file)
132 return SandboxedVfsFileType::kJournal;
134 const char* wal_file_cstr = sqlite3_filename_wal(full_path_cstr);
135 base::StringPiece wal_file(wal_file_cstr);
136 if (full_path == wal_file)
137 return SandboxedVfsFileType::kWal;
140 << "Argument is not a file name buffer passed from SQLite to a VFS: "
142 return SandboxedVfsFileType::kDatabase;
144 #endif // DCHECK_IS_ON()
149 void SandboxedVfs::Register(const char* name,
150 std::unique_ptr<Delegate> delegate,
152 static base::NoDestructor<std::vector<SandboxedVfs*>>
153 registered_vfs_instances;
154 sql::EnsureSqliteInitialized();
155 registered_vfs_instances->push_back(
156 new SandboxedVfs(name, std::move(delegate), make_default));
159 int SandboxedVfs::Open(const char* full_path,
160 sqlite3_file& result_file,
162 int* granted_flags) {
163 base::FilePath file_path = base::FilePath::FromUTF8Unsafe(full_path);
164 base::File file = delegate_->OpenFile(file_path, requested_flags);
165 if (!file.IsValid()) {
166 // TODO(pwnall): Figure out if we can remove the fallback to read-only.
167 if (!(requested_flags & SQLITE_OPEN_READWRITE)) {
168 // The SQLite API requires that pMethods is set to null even if the open
169 // call returns a failure status.
170 result_file.pMethods = nullptr;
171 return SQLITE_CANTOPEN;
175 (requested_flags & ~SQLITE_OPEN_READWRITE) | SQLITE_OPEN_READONLY;
176 return Open(full_path, result_file, new_flags, granted_flags);
179 SandboxedVfsFile::Create(std::move(file), std::move(file_path),
181 VfsFileTypeFromPath(full_path),
182 #endif // DCHECK_IS_ON()
185 *granted_flags = requested_flags;
189 int SandboxedVfs::Delete(const char* full_path, int sync_dir) {
191 return delegate_->DeleteFile(base::FilePath::FromUTF8Unsafe(full_path),
195 int SandboxedVfs::Access(const char* full_path, int flags, int& result) {
197 absl::optional<PathAccessInfo> access =
198 delegate_->GetPathAccess(base::FilePath::FromUTF8Unsafe(full_path));
205 case SQLITE_ACCESS_EXISTS:
208 case SQLITE_ACCESS_READ:
209 result = access->can_read ? 1 : 0;
211 case SQLITE_ACCESS_READWRITE:
212 result = (access->can_read && access->can_write) ? 1 : 0;
215 NOTREACHED() << "Unsupported xAccess flags: " << flags;
221 int SandboxedVfs::FullPathname(const char* file_path,
225 DCHECK_GT(result_size, 0);
228 // Renderer processes cannot access files directly, so it doesn't make sense
229 // to expose full paths here.
230 size_t file_path_size = std::strlen(file_path) + 1;
231 if (static_cast<size_t>(result_size) < file_path_size)
232 return SQLITE_CANTOPEN;
233 std::memcpy(result, file_path, file_path_size);
237 int SandboxedVfs::Randomness(int result_size, char* result) {
238 DCHECK_GT(result_size, 0);
241 // TODO(pwnall): Figure out if we need a real implementation.
242 std::memset(result, 0, result_size);
246 int SandboxedVfs::Sleep(int microseconds) {
247 DCHECK_GE(microseconds, 0);
248 base::PlatformThread::Sleep(base::Microseconds(microseconds));
252 int SandboxedVfs::GetLastError(int message_size, char* message) const {
253 DCHECK_GE(message_size, 0);
254 DCHECK(message_size == 0 || message);
256 std::string error_string = base::File::ErrorToString(last_error_);
257 size_t error_string_size = error_string.length() + 1;
259 std::min(static_cast<size_t>(message_size), error_string_size);
260 std::memcpy(message, error_string.c_str(), copy_length);
261 // The return value is zero if the message fits in the buffer, and non-zero if
263 return copy_length != error_string_size;
266 int SandboxedVfs::CurrentTimeInt64(sqlite3_int64* result_ms) {
269 base::TimeDelta delta = base::Time::Now() - sqlite_epoch_;
270 *result_ms = delta.InMilliseconds();
274 SandboxedVfs::SandboxedVfs(const char* name,
275 std::unique_ptr<Delegate> delegate,
277 : sandboxed_vfs_(SqliteVfsFor(this, name)),
278 sqlite_epoch_(SqliteEpoch()),
279 delegate_(std::move(delegate)),
280 last_error_(base::File::FILE_OK) {
281 // The register function returns a SQLite status as an int. The status is
282 // ignored here. If registration fails, we'd want to report the error while
283 // attempting to open a database. This is exactly what will happen, because
284 // SQLite won't find the VFS we're asking for.
285 sqlite3_vfs_register(&sandboxed_vfs_, make_default ? 1 : 0);