File: backend_storage_delegate.cc

package info (click to toggle)
chromium 144.0.7559.109-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 5,915,868 kB
  • sloc: cpp: 35,866,215; ansic: 7,599,035; javascript: 3,623,761; python: 1,639,407; xml: 833,084; asm: 716,173; pascal: 185,323; sh: 88,763; perl: 88,699; objc: 79,984; sql: 58,217; cs: 42,430; fortran: 24,101; makefile: 20,747; tcl: 15,277; php: 14,022; yacc: 9,059; ruby: 7,553; awk: 3,720; lisp: 3,233; lex: 1,330; ada: 727; jsp: 228; sed: 36
file content (265 lines) | stat: -rw-r--r-- 9,826 bytes parent folder | download | duplicates (3)
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
// Copyright 2025 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "components/persistent_cache/sqlite/backend_storage_delegate.h"

#include <memory>
#include <utility>

#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/metrics/histogram_functions.h"
#include "base/numerics/clamped_math.h"
#include "base/types/expected_macros.h"
#include "components/persistent_cache/pending_backend.h"
#include "components/persistent_cache/sqlite/constants.h"
#include "components/persistent_cache/sqlite/sqlite_backend_impl.h"
#include "components/persistent_cache/sqlite/vfs/sqlite_database_vfs_file_set.h"

#if BUILDFLAG(IS_WIN)
#include <windows.h>
#endif

namespace persistent_cache::sqlite {

namespace {

// Returns a duplicate of `source_file` (at `source_file_path`) which has either
// read-only (`source_is_read_write` = false) or read-write (otherwise) access
// that, itself, has either read-only (`target_read_write` = false) or
// read-write access.
base::File DuplicateFile(const base::File& source_file,
                         const base::FilePath& source_file_path,
                         bool source_is_read_write,
                         bool target_read_write) {
  CHECK(source_file.IsValid());
  // Can't upgrade from read-only to read-write.
  CHECK(!target_read_write || source_is_read_write);

  if (source_is_read_write == target_read_write) {
    // Caller requests the same rights. Simple duplication as-is.
    return source_file.Duplicate();
  }

#if BUILDFLAG(IS_WIN)
  // Duplicate the handle to the file with restricted rights.
  HANDLE handle = nullptr;
  if (!::DuplicateHandle(
          /*hSourceProcessHandle=*/::GetCurrentProcess(),
          /*hSourceHandle=*/source_file.GetPlatformFile(),
          /*hTargetProcessHandle=*/::GetCurrentProcess(),
          /*lpTargetHandle=*/&handle,
          /*dwDesiredAccess=*/FILE_GENERIC_READ,
          /*bInheritHandle=*/FALSE,
          /*dwOptions=*/0)) {
    // Duplication failed; return an invalid File.
    DWORD error = ::GetLastError();
    return base::File(base::File::OSErrorToFileError(error));
  }
  return base::File(handle);
#else
  // It's not possible to get a new file descriptor with reduced permissions to
  // the same file description, so open the file anew with read-only access.
  return base::File(source_file_path,
                    base::File::FLAG_OPEN | base::File::FLAG_READ);
#endif
}

}  // namespace

std::optional<PendingBackend> BackendStorageDelegate::MakePendingBackend(
    const base::FilePath& directory,
    const base::FilePath& base_name,
    bool single_connection,
    bool journal_mode_wal) {
  // Write-ahead logging journaling is only supported for single connections.
  CHECK(!journal_mode_wal || single_connection);
  PendingBackend pending_backend;

  uint32_t create_flags = base::File::FLAG_OPEN_ALWAYS | base::File::FLAG_READ |
                          base::File::FLAG_WRITE |
                          base::File::FLAG_WIN_SHARE_DELETE |
                          base::File::FLAG_CAN_DELETE_ON_CLOSE;

  if (single_connection) {
    // If only a single connection is allowed, there is no need to allow others
    // to open the files for reading or writing. Delete is always allowed so
    // that the files can be deleted even while in-use.
    create_flags |= base::File::FLAG_WIN_EXCLUSIVE_READ |
                    base::File::FLAG_WIN_EXCLUSIVE_WRITE;
  }

  // Make sure handles to these files are safe to pass to untrusted processes.
  create_flags = base::File::AddFlagsForPassingToUntrustedProcess(create_flags);

  auto db_file_path =
      directory.Append(base_name).AddExtension(kDbFileExtension);
  pending_backend.sqlite_data.db_file = base::File(db_file_path, create_flags);
  if (!pending_backend.sqlite_data.db_file.IsValid()) {
    base::UmaHistogramExactLinear(
        "PersistentCache.Sqlite.DbFile.CreateError",
        -pending_backend.sqlite_data.db_file.error_details(),
        -base::File::FILE_ERROR_MAX);
    return std::nullopt;
  }

  auto journal_file_path =
      directory.Append(base_name).AddExtension(kJournalFileExtension);
  pending_backend.sqlite_data.journal_file =
      base::File(journal_file_path, create_flags);
  if (!pending_backend.sqlite_data.journal_file.IsValid()) {
    base::UmaHistogramExactLinear(
        "PersistentCache.Sqlite.JournalFile.CreateError",
        -pending_backend.sqlite_data.journal_file.error_details(),
        -base::File::FILE_ERROR_MAX);
    return std::nullopt;
  }

  if (journal_mode_wal) {
    auto wal_file_path =
        directory.Append(base_name).AddExtension(kWalJournalFileExtension);
    pending_backend.sqlite_data.wal_file =
        base::File(wal_file_path, create_flags);
    if (!pending_backend.sqlite_data.wal_file.IsValid()) {
      base::UmaHistogramExactLinear(
          "PersistentCache.Sqlite.WalJournalFile.CreateError",
          -pending_backend.sqlite_data.wal_file.error_details(),
          -base::File::FILE_ERROR_MAX);
      return std::nullopt;
    }
  }

  if (!single_connection) {
    // The shared lock is only needed if multiple connections are permitted.
    pending_backend.sqlite_data.shared_lock =
        base::UnsafeSharedMemoryRegion::Create(sizeof(SharedAtomicLock));
    if (!pending_backend.sqlite_data.shared_lock.IsValid()) {
      return std::nullopt;
    }
  }

  pending_backend.read_write = true;

  return pending_backend;
}

std::unique_ptr<Backend> BackendStorageDelegate::MakeBackend(
    const base::FilePath& directory,
    const base::FilePath& base_name,
    bool single_connection,
    bool journal_mode_wal) {
  if (auto pending_backend = MakePendingBackend(
          directory, base_name, single_connection, journal_mode_wal);
      pending_backend.has_value()) {
    return SqliteBackendImpl::Bind(*std::move(pending_backend));
  }
  return nullptr;
}

std::optional<PendingBackend> BackendStorageDelegate::ShareReadOnlyConnection(
    const base::FilePath& directory,
    const base::FilePath& base_name,
    const Backend& backend) {
  return ShareConnection(
      directory, base_name,
      static_cast<const SqliteBackendImpl&>(backend).file_set(),
      /*read_write=*/false);
}

std::optional<PendingBackend> BackendStorageDelegate::ShareReadWriteConnection(
    const base::FilePath& directory,
    const base::FilePath& base_name,
    const Backend& backend) {
  return ShareConnection(
      directory, base_name,
      static_cast<const SqliteBackendImpl&>(backend).file_set(),
      /*read_write=*/true);
}

base::FilePath BackendStorageDelegate::GetBaseName(const base::FilePath& file) {
  return file.MatchesFinalExtension(kDbFileExtension)
             ? file.BaseName().RemoveFinalExtension()
             : base::FilePath();
}

int64_t BackendStorageDelegate::DeleteFiles(const base::FilePath& directory,
                                            const base::FilePath& base_name) {
  auto file_path = directory.Append(base_name).AddExtension(kDbFileExtension);
  int64_t bytes_recovered = base::GetFileSize(file_path).value_or(0);
  bool delete_success = base::DeleteFile(file_path);
  base::UmaHistogramBoolean(
      "PersistentCache.ParamsManager.DbFile.DeleteSuccess", delete_success);
  if (!delete_success) {
    return 0;
  }

  file_path = directory.Append(base_name).AddExtension(kJournalFileExtension);
  auto file_size = base::GetFileSize(file_path).value_or(0);
  delete_success = base::DeleteFile(file_path);
  base::UmaHistogramBoolean(
      "PersistentCache.ParamsManager.JournalFile.DeleteSuccess",
      delete_success);
  if (delete_success) {
    bytes_recovered = base::ClampAdd(bytes_recovered, file_size);
  }

  file_path =
      directory.Append(base_name).AddExtension(kWalJournalFileExtension);
  file_size = base::GetFileSize(file_path).value_or(0);
  delete_success = base::DeleteFile(file_path);
  base::UmaHistogramBoolean(
      "PersistentCache.ParamsManager.WalJournalFile.DeleteSuccess",
      delete_success);
  if (delete_success) {
    bytes_recovered = base::ClampAdd(bytes_recovered, file_size);
  }

  // TODO (https://crbug.com/377475540): Cleanup when deletion of journal
  // failed.
  return bytes_recovered;
}

std::optional<PendingBackend> BackendStorageDelegate::ShareConnection(
    const base::FilePath& directory,
    const base::FilePath& base_name,
    const SqliteVfsFileSet& file_set,
    bool read_write) {
  // Cannot share a single-connection backend. If it ever becomes interesting to
  // connect to a backend in one process and then move it to another process,
  // we shall introduce a way to `Unbind()` a backend to convert it back into a
  // `PendingBackend`.
  CHECK(!file_set.is_single_connection());
  // All connections using a write-ahead log are single-connection.
  CHECK(!file_set.wal_journal_mode());

  PendingBackend pending_backend;

  pending_backend.sqlite_data.db_file =
      DuplicateFile(file_set.GetDbFile(),
                    directory.Append(base_name).AddExtension(kDbFileExtension),
                    !file_set.read_only(), read_write);
  if (!pending_backend.sqlite_data.db_file.IsValid()) {
    return std::nullopt;
  }

  pending_backend.sqlite_data.journal_file = DuplicateFile(
      file_set.GetJournalFile(),
      directory.Append(base_name).AddExtension(kJournalFileExtension),
      !file_set.read_only(), read_write);
  if (!pending_backend.sqlite_data.journal_file.IsValid()) {
    return std::nullopt;
  }

  pending_backend.sqlite_data.shared_lock =
      file_set.GetSharedLock().Duplicate();
  if (!pending_backend.sqlite_data.shared_lock.IsValid()) {
    return std::nullopt;
  }

  pending_backend.read_write = read_write;

  return pending_backend;
}

}  // namespace persistent_cache::sqlite