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
|
// 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 "net/http/no_vary_search_cache_storage_file_operations.h"
#include <stdint.h>
#include "net/http/no_vary_search_cache_storage.h"
#if BUILDFLAG(IS_WIN)
#include <windows.h> // For {Get,Set}FileAttributes
#endif // BUILDFLAG(IS_WIN)
#include <algorithm>
#include <type_traits>
#include <utility>
#include "base/check_op.h"
#include "base/files/file.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/metrics/histogram_functions.h"
#include "base/numerics/safe_math.h"
#include "base/pickle.h"
#include "base/sequence_checker.h"
#include "base/strings/strcat.h"
#include "base/strings/string_util.h"
#include "base/time/time.h"
#if BUILDFLAG(IS_WIN)
#include "base/threading/platform_thread.h" // for PlatformThread::Sleep()
#endif // BUILDFLAG(IS_WIN)
namespace net {
namespace {
// NoVarySearchCacheStorageFileOperations is a very long name.
using FileOperations = NoVarySearchCacheStorageFileOperations;
using enum base::File::Error;
// Implementation of FileOperations::Writer that appends to a real file.
class RealWriter final : public FileOperations::Writer {
public:
explicit RealWriter(base::File file) : file_(std::move(file)) {}
~RealWriter() override { DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); }
bool Write(base::span<const uint8_t> data) override {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
return file_.WriteAtCurrentPosAndCheck(data);
}
private:
base::File file_ GUARDED_BY_CONTEXT(sequence_checker_);
SEQUENCE_CHECKER(sequence_checker_);
};
// True if `filename` should be accepted by FileOperations methods.
bool IsAcceptableFilename(std::string_view filename) {
return base::IsStringASCII(filename) &&
std::ranges::none_of(filename, base::FilePath::IsSeparator) &&
filename != "." && filename != "..";
}
// Creates the directory `path` and all non-existent parent directories if
// possible. Reports the results to histograms using `histogram_suffix`.
bool CreateDirectoryIfNotExists(const base::FilePath& path,
std::string_view histogram_suffix) {
// The result of trying to create the directory.
//
// These values are persisted to logs. Entries should not be renumbered and
// numeric values should never be reused.
//
// LINT.IfChange(CreateDirectoryResult)
enum class CreateDirectoryResult {
kAlreadyExisted = 0,
kCreated = 1,
kCreateFailed = 2,
kMaxValue = kCreateFailed,
};
// LINT.ThenChange(//tools/metrics/histograms/metadata/net/enums.xml:NoVarySearchDirectoryCreateResult)
const CreateDirectoryResult result = [&] {
if (base::DirectoryExists(path)) {
return CreateDirectoryResult::kAlreadyExisted;
}
base::File::Error error;
if (!base::CreateDirectoryAndGetError(path, &error)) {
base::UmaHistogramExactLinear(
base::StrCat({"HttpCache.NoVarySearch.DirectoryCreateError.",
histogram_suffix}),
-error, -FILE_ERROR_MAX);
return CreateDirectoryResult::kCreateFailed;
}
return CreateDirectoryResult::kCreated;
}();
base::UmaHistogramEnumeration(
base::StrCat(
{"HttpCache.NoVarySearch.DirectoryCreateResult.", histogram_suffix}),
result);
return result != CreateDirectoryResult::kCreateFailed;
}
// Deletes `path`. Returns true on success. Logs the error code to the histogram
// named by concatenating `histogram_name_parts` and returns false if deletion
// fails.
bool DeleteLoggingErrors(
const base::FilePath& path,
base::span<const std::string_view> histogram_name_parts) {
if (base::DeleteFile(path)) {
return true;
}
base::UmaHistogramExactLinear(base::StrCat(histogram_name_parts),
-base::File::GetLastFileError(),
-FILE_ERROR_MAX);
return false;
}
// Renames `old_path` to `new_path` if `old_path` exists and `new_path` does
// not. If both exist, deletes `old_path`. Records results to histograms using
// `histogram_suffix`.
void RenameOrDeleteIfExists(const base::FilePath& old_path,
const base::FilePath& new_path,
std::string_view histogram_suffix) {
// The result of the attempted rename or delete operation.
//
// These values are persisted to logs. Entries should not be renumbered and
// numeric values should never be reused.
//
// LINT.IfChange(RenameResult)
enum class RenameResult {
kSourceDidNotExist = 0,
kSourceDeleted = 1,
kDeletionFailed = 2,
kRenamed = 3,
kRenameFailed = 4,
kMaxValue = kRenameFailed,
};
// LINT.ThenChange(//tools/metrics/histograms/metadata/net/enums.xml:NoVarySearchRenameOrDeleteResult)
const RenameResult result = [&] {
if (!base::PathExists(old_path)) {
return RenameResult::kSourceDidNotExist;
}
if (base::PathExists(new_path)) {
return DeleteLoggingErrors(
old_path,
{"HttpCache.NoVarySearch.InitDeleteError.", histogram_suffix})
? RenameResult::kSourceDeleted
: RenameResult::kDeletionFailed;
}
base::File::Error error;
if (!base::ReplaceFile(old_path, new_path, &error)) {
// We don't attempt retries on Windows. If something has the file open we
// just give up. This rename functionality is purely best-effort and it's
// not critical if it fails, as the NoVarySearchCache will just be
// recreated.
base::UmaHistogramExactLinear(
base::StrCat(
{"HttpCache.NoVarySearch.InitRenameError.", histogram_suffix}),
-error, -FILE_ERROR_MAX);
return RenameResult::kRenameFailed;
}
return RenameResult::kRenamed;
}();
base::UmaHistogramEnumeration(
base::StrCat(
{"HttpCache.NoVarySearch.RenameOrDeleteResult.", histogram_suffix}),
result);
}
constexpr std::string_view kSnapshotFilename =
NoVarySearchCacheStorage::kSnapshotFilename;
void MoveOldFilesIfNeeded(const base::FilePath& parent_path,
const base::FilePath& path) {
static constexpr std::string_view kJournalFilename =
NoVarySearchCacheStorage::kJournalFilename;
RenameOrDeleteIfExists(parent_path.AppendASCII(kSnapshotFilename),
path.AppendASCII(kSnapshotFilename), "Snapshot");
RenameOrDeleteIfExists(parent_path.AppendASCII(kJournalFilename),
path.AppendASCII(kJournalFilename), "Journal");
}
void DeleteIfExists(const base::FilePath& path,
std::string_view histogram_suffix) {
// base::DeleteFile actually already tests if the file exists, but since it
// almost always won't we can save some time by doing it ourselves.
if (!base::PathExists(path)) {
return;
}
DeleteLoggingErrors(
path, {"HttpCache.NoVarySearch.DeleteIfExistsError.", histogram_suffix});
}
void DeleteTempFilesIfNeeded(const base::FilePath& parent_path,
const base::FilePath& path) {
const std::string snapshot_tempfile =
base::StrCat({kSnapshotFilename, "-new"});
DeleteIfExists(parent_path.AppendASCII(snapshot_tempfile), "Parent");
DeleteIfExists(path.AppendASCII(snapshot_tempfile), "NoVarySearch");
}
#if BUILDFLAG(IS_WIN)
// Attempt to replace `destination` with `source`, retrying on failure. Only
// needed on Windows, because only on Windows do virus checkers and other
// software open files preventing you from renaming them. Based on code from
// //base/files/important_file_writer.cc. Function signature must match
// base::ReplaceFile().
bool ReplaceFileWithRetries(const base::FilePath& source,
const base::FilePath& destination,
base::File::Error* error) {
// These settings are more aggressive than used by ImportantFileWriter.
static constexpr int kReplaceRetries = 50;
static constexpr base::TimeDelta kReplacePauseInterval =
base::Milliseconds(10);
// Unlike ImportantFileWriter, we don't try to boost priority to win the race
// against virus checkers and other interfering software, instead just relying
// on being persistent.
int try_count = 0;
bool result = false;
base::File::Error last_error = base::File::FILE_OK;
for (; !result && try_count < kReplaceRetries; ++try_count) {
result = base::ReplaceFile(source, destination, &last_error);
if (result) {
break;
}
if (last_error == base::File::FILE_ERROR_ACCESS_DENIED) {
// Attempt to fix permission problems. Avoid doing this by
// default because it's not actually atomic.
DWORD attrs = ::GetFileAttributes(destination.value().c_str());
if (attrs != INVALID_FILE_ATTRIBUTES) {
::SetFileAttributes(destination.value().c_str(),
attrs & ~FILE_ATTRIBUTE_READONLY);
}
} else if (last_error != base::File::FILE_ERROR_IN_USE) {
// We don't expect to recover from this error by retry, so just give up.
break;
}
base::PlatformThread::Sleep(kReplacePauseInterval);
}
if (result) {
base::UmaHistogramExactLinear("HttpCache.NoVarySearch.ReplaceFileTryCount",
try_count, kReplaceRetries);
} else {
*error = last_error;
}
return result;
}
#endif // BUILDFLAG(IS_WIN)
// Implementation of FileOperations that operates on real files.
class RealFileOperations : public FileOperations {
public:
using enum base::File::Flags;
explicit RealFileOperations(const base::FilePath& path)
: parent_path_(path), path_(path.AppendASCII(kNoVarySearchDirName)) {
// It's normal to construct this on a different thread than it will be used.
DETACH_FROM_SEQUENCE(sequence_checker_);
}
~RealFileOperations() override {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
}
bool Init() override {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
if (!CreateDirectoryIfNotExists(parent_path_,
/*histogram_suffix=*/"Parent") ||
!CreateDirectoryIfNotExists(path_,
/*histogram_suffix=*/"NoVarySearch")) {
return false;
}
// TODO(https://crbug.com/421927600): Remove this in December 2025 provided
// the kSourceDidNotExist bucket of the
// HttpCache.NoVarySearch.RenameOrDeleteResult.Snapshot histogram has
// reached 100%.
MoveOldFilesIfNeeded(parent_path_, path_);
DeleteTempFilesIfNeeded(parent_path_, path_);
return true;
}
base::expected<LoadResult, base::File::Error> Load(std::string_view filename,
size_t max_size) override {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
const base::FilePath path = GetPath(filename);
if (path.empty()) {
return base::unexpected(FILE_ERROR_SECURITY);
}
base::File file(path, FLAG_OPEN | FLAG_READ);
if (!file.IsValid()) {
return base::unexpected(file.error_details());
}
base::File::Info info;
if (!file.GetInfo(&info)) {
return base::unexpected(FILE_ERROR_FAILED);
}
CHECK_GE(info.size, 0);
if (base::StrictNumeric(info.size) > max_size) {
return base::unexpected(FILE_ERROR_NO_MEMORY);
}
// This cast is safe because we checked that 0 <= info.size <= max_size, and
// max_size is a size_t.
const size_t size = static_cast<size_t>(info.size);
LoadResult result;
result.contents.resize(size);
result.last_modified = info.last_modified;
std::optional<size_t> maybe_bytes = file.ReadAtCurrentPos(result.contents);
if (!maybe_bytes) {
return base::unexpected(FILE_ERROR_IO);
}
size_t read_bytes = maybe_bytes.value();
CHECK_LE(read_bytes, size);
if (read_bytes < size) {
// The file shrank.
result.contents.resize(read_bytes);
}
return result;
}
base::expected<void, base::File::Error> AtomicSave(
std::string_view filename,
base::span<const base::span<const uint8_t>> segments) override {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
base::FilePath path = GetPath(filename);
if (path.empty()) {
return base::unexpected(FILE_ERROR_SECURITY);
}
// Use a consistent temporary file name so that it will eventually be
// cleaned up on a future run if we crash.
base::FilePath temp_path = path.InsertBeforeExtensionASCII("-new");
// To defend against permission problems, delete `temp_path` if it already
// exists. It doesn't matter if this fails.
base::DeleteFile(temp_path);
base::File temp_file(temp_path, FLAG_CREATE_ALWAYS | FLAG_WRITE);
if (!temp_file.IsValid()) {
return base::unexpected(temp_file.error_details());
}
for (auto segment : segments) {
if (segment.empty()) {
continue;
}
if (!temp_file.WriteAtCurrentPosAndCheck(segment)) {
return base::unexpected(FILE_ERROR_IO);
}
}
temp_file.Close();
auto replace_file_func = base::ReplaceFile;
#if BUILDFLAG(IS_WIN)
replace_file_func = ReplaceFileWithRetries;
#endif
base::File::Error replace_error = FILE_OK;
if (!replace_file_func(temp_path, path, &replace_error)) {
base::UmaHistogramExactLinear("HttpCache.NoVarySearch.ReplaceFileError",
-replace_error, -FILE_ERROR_MAX);
return base::unexpected(replace_error);
}
return base::ok();
}
base::expected<std::unique_ptr<Writer>, base::File::Error> CreateWriter(
std::string_view filename) override {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
base::FilePath path = GetPath(filename);
if (path.empty()) {
return base::unexpected(FILE_ERROR_SECURITY);
}
// To defend against permission problems, delete `path` if it already
// exists. Ignore errors.
base::DeleteFile(path);
base::File file(path, FLAG_CREATE_ALWAYS | FLAG_WRITE);
if (!file.IsValid()) {
return base::unexpected(file.error_details());
}
return std::make_unique<RealWriter>(std::move(file));
}
private:
base::FilePath GetPath(std::string_view filename)
VALID_CONTEXT_REQUIRED(sequence_checker_) {
if (!IsAcceptableFilename(filename)) {
return base::FilePath();
}
return path_.AppendASCII(filename);
}
const base::FilePath parent_path_ GUARDED_BY_CONTEXT(sequence_checker_);
const base::FilePath path_ GUARDED_BY_CONTEXT(sequence_checker_);
SEQUENCE_CHECKER(sequence_checker_);
};
} // namespace
FileOperations::LoadResult::LoadResult() = default;
FileOperations::LoadResult::LoadResult(const LoadResult&) = default;
FileOperations::LoadResult::LoadResult(LoadResult&&) = default;
FileOperations::LoadResult& FileOperations::LoadResult::operator=(
const LoadResult&) = default;
FileOperations::LoadResult& FileOperations::LoadResult::operator=(
LoadResult&&) = default;
FileOperations::LoadResult::~LoadResult() = default;
FileOperations::Writer::~Writer() = default;
NoVarySearchCacheStorageFileOperations::
~NoVarySearchCacheStorageFileOperations() = default;
std::unique_ptr<FileOperations> FileOperations::Create(
const base::FilePath& path) {
return std::make_unique<RealFileOperations>(path);
}
} // namespace net
|