Skip to content

Commit

Permalink
[FilesTrash] Extract common validation logic for .trashinfo files
Browse files Browse the repository at this point in the history
The validation of .trashinfo files will be shared between the
fileManagerPrivate API and the RestoreIOTask. This extracts the
centralises the validation logic into a single class that also manages
the launching and lifetime of the TrashInfoParser.

Bug: b:238946031
Test: unit_tests --gtest_filter=*RestoreIOTask*
Change-Id: I87ff2e963de199720a3e69034a543801a14e0761
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/3818750
Commit-Queue: Ben Reich <benreich@chromium.org>
Reviewed-by: Luciano Pacheco <lucmult@chromium.org>
Cr-Commit-Position: refs/heads/main@{#1033299}
  • Loading branch information
ben-reich authored and Chromium LUCI CQ committed Aug 10, 2022
1 parent d2d9b88 commit 788e028
Show file tree
Hide file tree
Showing 7 changed files with 288 additions and 114 deletions.
2 changes: 2 additions & 0 deletions chrome/browser/ash/BUILD.gn
Expand Up @@ -1011,6 +1011,8 @@ source_set("ash") {
"file_manager/speedometer.h",
"file_manager/trash_common_util.cc",
"file_manager/trash_common_util.h",
"file_manager/trash_info_validator.cc",
"file_manager/trash_info_validator.h",
"file_manager/trash_io_task.cc",
"file_manager/trash_io_task.h",
"file_manager/url_util.cc",
Expand Down
103 changes: 15 additions & 88 deletions chrome/browser/ash/file_manager/restore_io_task.cc
Expand Up @@ -7,7 +7,6 @@
#include "base/callback.h"
#include "base/files/file.h"
#include "base/files/file_util.h"
#include "base/strings/string_piece.h"
#include "base/task/bind_post_task.h"
#include "base/task/task_traits.h"
#include "base/task/thread_pool.h"
Expand Down Expand Up @@ -78,13 +77,10 @@ void RestoreIOTask::Execute(IOTask::ProgressCallback progress_callback,
return;
}

enabled_trash_locations_ =
GenerateEnabledTrashLocationsForProfile(profile_, base_path_);
progress_.state = State::kInProgress;

parser_ = std::make_unique<chromeos::trash_service::TrashInfoParser>(
base::BindOnce(&RestoreIOTask::Complete, weak_ptr_factory_.GetWeakPtr(),
State::kError));
validator_ = std::make_unique<TrashInfoValidator>(profile_, base_path_);
validator_->SetDisconnectHandler(base::BindOnce(
&RestoreIOTask::Complete, weak_ptr_factory_.GetWeakPtr(), State::kError));

ValidateTrashInfo(0);
}
Expand All @@ -104,101 +100,32 @@ void RestoreIOTask::ValidateTrashInfo(size_t idx) {
(base_path_.empty())
? progress_.sources[idx].url.path()
: base_path_.Append(progress_.sources[idx].url.path());
if (trash_info.FinalExtension() != kTrashInfoExtension) {
progress_.sources[idx].error = base::File::FILE_ERROR_INVALID_URL;
Complete(State::kError);
return;
}

// Ensures the trash location is parented at an enabled trash location.
base::FilePath trash_folder_location;
base::FilePath mount_point_path;
for (const auto& [parent_path, info] : enabled_trash_locations_) {
if (parent_path.Append(info.relative_folder_path).IsParent(trash_info)) {
trash_folder_location = parent_path.Append(info.relative_folder_path);
mount_point_path = info.mount_point_path;
break;
}
}

if (mount_point_path.empty() || trash_folder_location.empty()) {
progress_.sources[idx].error = base::File::FILE_ERROR_INVALID_OPERATION;
Complete(State::kError);
return;
}

// Ensure the corresponding file that this metadata file refers to actually
// exists.
base::FilePath trashed_file_location =
trash_folder_location.Append(kFilesFolderName)
.Append(trash_info.BaseName().RemoveFinalExtension());

base::ThreadPool::PostTaskAndReplyWithResult(
FROM_HERE, {base::MayBlock()},
base::BindOnce(&base::PathExists, trashed_file_location),
base::BindOnce(&RestoreIOTask::OnTrashedFileExists,
weak_ptr_factory_.GetWeakPtr(), idx, mount_point_path,
trashed_file_location));
}

void RestoreIOTask::OnTrashedFileExists(
size_t idx,
const base::FilePath& mount_point_path,
const base::FilePath& trashed_file_location,
bool exists) {
if (!exists) {
progress_.sources[idx].error = base::File::FILE_ERROR_NOT_FOUND;
Complete(State::kError);
return;
}

auto complete_callback = base::BindPostTask(
base::SequencedTaskRunnerHandle::Get(),
auto on_parsed_callback =
base::BindOnce(&RestoreIOTask::EnsureParentRestorePathExists,
weak_ptr_factory_.GetWeakPtr(), idx, mount_point_path,
trashed_file_location));

base::FilePath trashinfo_path =
(base_path_.empty())
? progress_.sources[idx].url.path()
: base_path_.Append(progress_.sources[idx].url.path());
weak_ptr_factory_.GetWeakPtr(), idx);

parser_->ParseTrashInfoFile(std::move(trashinfo_path),
std::move(complete_callback));
validator_->ValidateAndParseTrashInfo(std::move(trash_info),
std::move(on_parsed_callback));
}

void RestoreIOTask::EnsureParentRestorePathExists(
size_t idx,
const base::FilePath& mount_point_path,
const base::FilePath& trashed_file_location,
base::File::Error status,
const base::FilePath& restore_path,
base::Time deletion_date) {
if (status != base::File::FILE_OK) {
progress_.sources[idx].error = status;
Complete(State::kError);
return;
}

if (restore_path.empty() ||
restore_path.value()[0] != base::FilePath::kSeparators[0]) {
progress_.sources[idx].error = base::File::FILE_ERROR_INVALID_URL;
base::FileErrorOr<ParsedTrashInfoData> parsed_data) {
if (parsed_data.is_error()) {
progress_.sources[idx].error = parsed_data.error();
Complete(State::kError);
return;
}

// Remove the leading "/" character to make the restore path relative from the
// known trash parent path.
base::StringPiece relative_path =
base::StringPiece(restore_path.value()).substr(1);
base::FilePath absolute_restore_path = mount_point_path.Append(relative_path);

base::ThreadPool::PostTaskAndReplyWithResult(
FROM_HERE, {base::MayBlock()},
base::BindOnce(&CreateNestedPath, absolute_restore_path.DirName()),
base::BindOnce(&CreateNestedPath,
parsed_data.value().absolute_restore_path.DirName()),
base::BindOnce(&RestoreIOTask::OnParentRestorePathExists,
weak_ptr_factory_.GetWeakPtr(), idx, trashed_file_location,
absolute_restore_path));
weak_ptr_factory_.GetWeakPtr(), idx,
parsed_data.value().trashed_file_path,
parsed_data.value().absolute_restore_path));
}

void RestoreIOTask::OnParentRestorePathExists(
Expand Down
28 changes: 6 additions & 22 deletions chrome/browser/ash/file_manager/restore_io_task.h
Expand Up @@ -11,7 +11,7 @@
#include "base/memory/weak_ptr.h"
#include "chrome/browser/ash/file_manager/io_task.h"
#include "chrome/browser/ash/file_manager/trash_common_util.h"
#include "chromeos/ash/components/trash_service/public/cpp/trash_info_parser.h"
#include "chrome/browser/ash/file_manager/trash_info_validator.h"
#include "storage/browser/file_system/file_system_context.h"
#include "storage/browser/file_system/file_system_operation_runner.h"
#include "storage/browser/file_system/file_system_url.h"
Expand Down Expand Up @@ -46,27 +46,15 @@ class RestoreIOTask : public IOTask {
// Finalises the RestoreIOTask with the `state`.
void Complete(State state);

// Ensure the metadata file conforms to the following:
// - Has a .trashinfo suffix
// - Resides in an enabled trash directory
// - The file resides in the info directory
// - Has an identical item in the files directory with no .trashinfo suffix
// Calls the underlying TrashInfoValidator to perform validation on the
// supplied .trashinfo file.
void ValidateTrashInfo(size_t idx);

void OnTrashedFileExists(size_t idx,
const base::FilePath& mount_point_path,
const base::FilePath& trashed_file_location,
bool exists);

// Make sure the enclosing folder where the trashed file to be restored to
// actually exists. In the event the file path has been removed, recreate it.
void EnsureParentRestorePathExists(
size_t idx,
const base::FilePath& mount_point_path,
const base::FilePath& trashed_file_location,
base::File::Error status,
const base::FilePath& restore_path,
base::Time deletion_date);
base::FileErrorOr<ParsedTrashInfoData> parsed_data);

void OnParentRestorePathExists(size_t idx,
const base::FilePath& trashed_file_location,
Expand Down Expand Up @@ -107,16 +95,12 @@ class RestoreIOTask : public IOTask {
// only in testing.
base::FilePath base_path_;

// A map containing paths which are enabled for trashing.
TrashPathsMap enabled_trash_locations_;

// Stores the id of the restore operation if one is in progress. Used so the
// restore can be cancelled.
absl::optional<storage::FileSystemOperationRunner::OperationID> operation_id_;

// Holds the connection open to the `TrashService`. This is a sandboxed
// process that performs parsing of the trashinfo files.
std::unique_ptr<chromeos::trash_service::TrashInfoParser> parser_ = nullptr;
// Validates and parses .trashinfo files.
std::unique_ptr<TrashInfoValidator> validator_ = nullptr;

ProgressCallback progress_callback_;
CompleteCallback complete_callback_;
Expand Down
146 changes: 146 additions & 0 deletions chrome/browser/ash/file_manager/trash_info_validator.cc
@@ -0,0 +1,146 @@
// Copyright 2022 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/ash/file_manager/trash_info_validator.h"

#include "base/files/file.h"
#include "base/files/file_util.h"
#include "base/strings/string_piece.h"
#include "base/task/bind_post_task.h"
#include "base/task/task_traits.h"
#include "base/task/thread_pool.h"
#include "base/threading/sequenced_task_runner_handle.h"

class Profile;

namespace file_manager {

namespace {

void RunCallbackWithError(base::File::Error error,
ValidateAndParseTrashInfoCallback callback) {
std::move(callback).Run(base::FileErrorOr<ParsedTrashInfoData>(error));
}

} // namespace

TrashInfoValidator::TrashInfoValidator(Profile* profile,
const base::FilePath& base_path) {
enabled_trash_locations_ =
io_task::GenerateEnabledTrashLocationsForProfile(profile, base_path);

parser_ = std::make_unique<chromeos::trash_service::TrashInfoParser>();
}

TrashInfoValidator::~TrashInfoValidator() = default;

void TrashInfoValidator::SetDisconnectHandler(
base::OnceCallback<void()> disconnect_callback) {
DCHECK(parser_) << "Parser should not be null here";
if (parser_) {
parser_->SetDisconnectHandler(std::move(disconnect_callback));
}
}

void TrashInfoValidator::ValidateAndParseTrashInfo(
const base::FilePath& trash_info_path,
ValidateAndParseTrashInfoCallback callback) {
// Validates the supplied file ends in a .trashinfo extension.
if (trash_info_path.FinalExtension() != io_task::kTrashInfoExtension) {
RunCallbackWithError(base::File::FILE_ERROR_INVALID_URL,
std::move(callback));
return;
}

// Validate the .trashinfo file belongs in an enabled trash location.
base::FilePath trash_folder_location;
base::FilePath mount_point_path;
for (const auto& [parent_path, info] : enabled_trash_locations_) {
if (parent_path.Append(info.relative_folder_path)
.IsParent(trash_info_path)) {
trash_folder_location = parent_path.Append(info.relative_folder_path);
mount_point_path = info.mount_point_path;
break;
}
}

if (mount_point_path.empty() || trash_folder_location.empty()) {
RunCallbackWithError(base::File::FILE_ERROR_INVALID_OPERATION,
std::move(callback));
return;
}

// Ensure the corresponding file that this metadata file refers to actually
// exists.
base::FilePath trashed_file_location =
trash_folder_location.Append(io_task::kFilesFolderName)
.Append(trash_info_path.BaseName().RemoveFinalExtension());

base::ThreadPool::PostTaskAndReplyWithResult(
FROM_HERE, {base::MayBlock()},
base::BindOnce(&base::PathExists, trashed_file_location),
base::BindOnce(&TrashInfoValidator::OnTrashedFileExists,
weak_ptr_factory_.GetWeakPtr(), mount_point_path,
trashed_file_location, std::move(trash_info_path),
std::move(callback)));
}

void TrashInfoValidator::OnTrashedFileExists(
const base::FilePath& mount_point_path,
const base::FilePath& trashed_file_location,
const base::FilePath& trash_info_path,
ValidateAndParseTrashInfoCallback callback,
bool exists) {
if (!exists) {
RunCallbackWithError(base::File::FILE_ERROR_NOT_FOUND, std::move(callback));
return;
}

auto complete_callback = base::BindPostTask(
base::SequencedTaskRunnerHandle::Get(),
base::BindOnce(&TrashInfoValidator::OnTrashInfoParsed,
weak_ptr_factory_.GetWeakPtr(), mount_point_path,
trashed_file_location, std::move(callback)));

parser_->ParseTrashInfoFile(std::move(trash_info_path),
std::move(complete_callback));
}

void TrashInfoValidator::OnTrashInfoParsed(
const base::FilePath& mount_point_path,
const base::FilePath& trashed_file_location,
ValidateAndParseTrashInfoCallback callback,
base::File::Error status,
const base::FilePath& restore_path,
base::Time deletion_date) {
if (status != base::File::FILE_OK) {
RunCallbackWithError(status, std::move(callback));
return;
}

// The restore path that was parsed could be empty or not have a leading "/".
if (restore_path.empty() ||
restore_path.value()[0] != base::FilePath::kSeparators[0]) {
RunCallbackWithError(base::File::FILE_ERROR_INVALID_URL,
std::move(callback));
return;
}

// Remove the leading "/" character to make the restore path relative from the
// known trash parent path.
base::StringPiece relative_path =
base::StringPiece(restore_path.value()).substr(1);
base::FilePath absolute_restore_path = mount_point_path.Append(relative_path);

ParsedTrashInfoData parsed_data = {
.trashed_file_path = std::move(trashed_file_location),
.absolute_restore_path = std::move(absolute_restore_path),
.deletion_date = std::move(deletion_date),
};

std::move(callback).Run(
base::FileErrorOr<ParsedTrashInfoData>(std::move(parsed_data)));
}

} // namespace file_manager

0 comments on commit 788e028

Please sign in to comment.