blob: f2c60874ca8c7884892e7bf59444095fb105aad8 [file]
// Copyright 2024 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/common/web_ui_loading_util.h"
#include <algorithm>
#include <cstdint>
#include <utility>
#include "base/byte_size.h"
#include "base/check.h"
#include "base/check_op.h"
#include "base/containers/span.h"
#include "base/feature_list.h"
#include "base/functional/bind.h"
#include "base/functional/callback_helpers.h"
#include "base/memory/ref_counted_memory.h"
#include "base/memory/scoped_refptr.h"
#include "base/numerics/safe_conversions.h"
#include "base/types/expected.h"
#include "content/common/features.h"
#include "content/public/common/content_client.h"
#include "mojo/public/cpp/bindings/pending_remote.h"
#include "mojo/public/cpp/bindings/remote.h"
#include "mojo/public/cpp/system/data_pipe.h"
#include "mojo/public/cpp/system/data_pipe_producer.h"
#include "net/http/http_byte_range.h"
#include "net/http/http_request_headers.h"
#include "net/http/http_util.h"
#include "services/network/public/cpp/loading_params.h"
#include "services/network/public/mojom/url_loader.mojom.h"
#include "services/network/public/mojom/url_response_head.mojom.h"
namespace content {
namespace webui {
namespace {
class MemoryDataSource : public mojo::DataPipeProducer::DataSource {
public:
MemoryDataSource(scoped_refptr<base::RefCountedMemory> data,
size_t offset,
size_t size)
: data_(std::move(data)), offset_(offset), size_(size) {}
uint64_t GetLength() const override { return size_; }
bool MayInspectReadBuffer() const override { return false; }
ReadResult Read(uint64_t offset, base::span<char> buffer) override {
ReadResult result;
CHECK_LT(offset, size_);
size_t copy_size =
std::min(buffer.size(), size_ - static_cast<size_t>(offset));
base::as_writable_bytes(buffer).copy_prefix_from(base::span(*data_).subspan(
offset_ + static_cast<size_t>(offset), copy_size));
result.bytes_read = copy_size;
result.result = MOJO_RESULT_OK;
return result;
}
private:
scoped_refptr<base::RefCountedMemory> data_;
size_t offset_;
size_t size_;
};
// Sends `headers` and the `output_size` bytes in `pipe` to the client.
void SendResponse(
network::mojom::URLResponseHeadPtr headers,
mojo::PendingRemote<network::mojom::URLLoaderClient> client_remote,
mojo::ScopedDataPipeConsumerHandle pipe,
size_t output_size) {
// For media content, |content_length| must be known upfront for data that is
// assumed to be fully buffered (as opposed to streamed from the network),
// otherwise the media player will get confused and refuse to play.
// Content delivered via chrome:// URLs is assumed fully buffered.
headers->content_length = output_size;
auto now_ticks = base::TimeTicks::Now();
headers->response_start = now_ticks;
headers->response_time = base::Time::Now();
headers->load_timing.receive_headers_start = now_ticks;
headers->load_timing.receive_headers_end = now_ticks;
mojo::Remote<network::mojom::URLLoaderClient> client(
std::move(client_remote));
client->OnReceiveResponse(std::move(headers), std::move(pipe), std::nullopt);
network::URLLoaderCompletionStatus status(net::OK);
status.encoded_data_length = base::ByteSize(output_size);
status.encoded_body_length = base::ByteSize(output_size);
status.decoded_body_length = base::ByteSize(output_size);
status.completion_time = base::TimeTicks::Now();
client->OnComplete(status);
}
// Attempts to load `resource_id` directly into a payload-sized Mojo data pipe.
// Returns an invalid handle if the resource cannot be loaded this way (e.g., it
// exceeds the max pipe capacity, is empty, or the embedder does not support
// direct loading).
std::pair<mojo::ScopedDataPipeConsumerHandle, size_t> TryLoadResourceIntoPipe(
ContentClient* content_client,
int resource_id) {
mojo::ScopedDataPipeProducerHandle producer_handle;
mojo::ScopedDataPipeConsumerHandle consumer_handle;
size_t output_size = 0;
uint32_t max_data_pipe_size = network::GetDataPipeDefaultAllocationSize(
network::DataPipeAllocationSize::kLargerSizeIfPossible);
bool loaded = content_client->LoadDataResourceInto(
resource_id, [&](size_t size) -> base::span<uint8_t> {
CHECK(!producer_handle.is_valid());
// A capacity of 0 would mean "use the default capacity".
if (size == 0 || size > max_data_pipe_size) {
return {};
}
base::span<uint8_t> buffer;
if (mojo::CreateDataPipe(base::checked_cast<uint32_t>(size),
producer_handle,
consumer_handle) != MOJO_RESULT_OK ||
producer_handle->BeginWriteData(size,
MOJO_BEGIN_WRITE_DATA_FLAG_NONE,
buffer) != MOJO_RESULT_OK ||
buffer.size() < size) {
producer_handle.reset();
consumer_handle.reset();
return {};
}
output_size = size;
return buffer.first(size);
});
if (!loaded) {
return {{}, 0};
}
CHECK(producer_handle.is_valid());
CHECK_EQ(producer_handle->EndWriteData(output_size), MOJO_RESULT_OK);
return {std::move(consumer_handle), output_size};
}
} // namespace
void CallOnError(
mojo::PendingRemote<network::mojom::URLLoaderClient> client_remote,
int error_code) {
mojo::Remote<network::mojom::URLLoaderClient> client(
std::move(client_remote));
network::URLLoaderCompletionStatus status;
status.error_code = error_code;
client->OnComplete(status);
}
base::expected<net::HttpByteRange, GetRequestedRangeError> GetRequestedRange(
const net::HttpRequestHeaders& headers) {
std::optional<std::string> range_header =
headers.GetHeader(net::HttpRequestHeaders::kRange);
if (!range_header) {
return base::unexpected(GetRequestedRangeError::kNoRanges);
}
std::vector<net::HttpByteRange> ranges;
if (!net::HttpUtil::ParseRangeHeader(*range_header, &ranges)) {
return base::unexpected(GetRequestedRangeError::kParseFailed);
}
if (ranges.size() > 1u) {
return base::unexpected(GetRequestedRangeError::kMultipleRanges);
}
return ranges[0];
}
bool SendData(
network::mojom::URLResponseHeadPtr headers,
mojo::PendingRemote<network::mojom::URLLoaderClient> client_remote,
std::optional<net::HttpByteRange> requested_range,
scoped_refptr<base::RefCountedMemory> bytes) {
// Mojo data pipe APIs use `uint32_t` for capacities, sizes, and offsets.
if (!base::IsValueInRangeForNumericType<uint32_t>(bytes->size())) {
CallOnError(std::move(client_remote), net::ERR_INSUFFICIENT_RESOURCES);
return false;
}
if (requested_range) {
if (!requested_range->ComputeBounds(bytes->size())) {
CallOnError(std::move(client_remote),
net::ERR_REQUEST_RANGE_NOT_SATISFIABLE);
return false;
}
}
auto [pipe, output_size] = GetPipe(bytes, requested_range);
if (!pipe.is_valid()) {
CallOnError(std::move(client_remote), net::ERR_INSUFFICIENT_RESOURCES);
return false;
}
SendResponse(std::move(headers), std::move(client_remote), std::move(pipe),
output_size);
return true;
}
bool SendDataResource(
network::mojom::URLResponseHeadPtr headers,
mojo::PendingRemote<network::mojom::URLLoaderClient> client_remote,
int resource_id) {
ContentClient* content_client = GetContentClient();
if (base::FeatureList::IsEnabled(
features::kWebUIDirectResourceDecompression)) {
auto [pipe, output_size] =
TryLoadResourceIntoPipe(content_client, resource_id);
if (pipe.is_valid()) {
SendResponse(std::move(headers), std::move(client_remote),
std::move(pipe), output_size);
return true;
}
}
scoped_refptr<base::RefCountedMemory> bytes =
content_client->GetDataResourceBytes(resource_id);
CHECK(bytes);
return SendData(std::move(headers), std::move(client_remote), std::nullopt,
std::move(bytes));
}
std::pair<mojo::ScopedDataPipeConsumerHandle, size_t> GetPipe(
scoped_refptr<base::RefCountedMemory> bytes,
std::optional<net::HttpByteRange> requested_range) {
CHECK(base::IsValueInRangeForNumericType<uint32_t>(bytes->size()));
uint32_t output_offset = 0;
size_t output_size = bytes->size();
if (requested_range) {
DCHECK(base::IsValueInRangeForNumericType<uint32_t>(
requested_range->first_byte_position()))
<< "Expecting ComputeBounds() to enforce it";
output_offset = requested_range->first_byte_position();
output_size = requested_range->last_byte_position() -
requested_range->first_byte_position() + 1;
}
const bool sync_write_enabled =
base::FeatureList::IsEnabled(features::kWebUISyncDataPipeWrite);
// `0` means using the default capacity.
uint32_t capacity_num_bytes = 0;
if (sync_write_enabled) {
const uint32_t max_data_pipe_size =
network::GetDataPipeDefaultAllocationSize(
network::DataPipeAllocationSize::kLargerSizeIfPossible);
capacity_num_bytes = std::clamp(base::checked_cast<uint32_t>(output_size),
1u, max_data_pipe_size);
}
mojo::ScopedDataPipeProducerHandle pipe_producer_handle;
mojo::ScopedDataPipeConsumerHandle pipe_consumer_handle;
MojoResult create_result = mojo::CreateDataPipe(
capacity_num_bytes, pipe_producer_handle, pipe_consumer_handle);
if (create_result != MOJO_RESULT_OK && capacity_num_bytes > 0) {
// Retry with the default pipe capacity if a sized allocation fails.
create_result = mojo::CreateDataPipe(
/*capacity_num_bytes=*/0u, pipe_producer_handle, pipe_consumer_handle);
}
if (create_result != MOJO_RESULT_OK) {
return std::make_pair(mojo::ScopedDataPipeConsumerHandle(), 0);
}
if (sync_write_enabled &&
pipe_producer_handle->WriteAllData(base::span(*bytes).subspan(
output_offset, output_size)) == MOJO_RESULT_OK) {
return std::make_pair(std::move(pipe_consumer_handle), output_size);
}
auto producer =
std::make_unique<mojo::DataPipeProducer>(std::move(pipe_producer_handle));
auto* producer_ptr = producer.get();
producer_ptr->Write(
std::make_unique<MemoryDataSource>(bytes, output_offset, output_size),
base::DoNothingWithBoundArgs(std::move(producer)));
return std::make_pair(std::move(pipe_consumer_handle), output_size);
}
} // namespace webui
} // namespace content