electron/shell/browser/net/asar/asar_url_loader.cc
Electron Bot bf6e4b1247 chore: bump chromium to 279aeeec3c9fe2237bc31f776f269 (master) (#21521)
* chore: bump chromium in DEPS to 46d2d82e84d73806da623c5333dae4dd218172df

* chore: bump chromium in DEPS to cbafe74731a5d1e59844ca59e0fc28f4a5f80a33

* chore: bump chromium in DEPS to d5dcd6b5cc76f4e1732083d775cdd7b533f0abe9

* Update patches

* update for lint

* Fix compilation errors

* chore: bump chromium in DEPS to 1c19360fdaaf65d4ed006736c7f9804104095990

* Replace removed constant

* chore: bump chromium in DEPS to 3b6639f5da26c1772c5d4f3ba634aca65df75fec

* chore: bump chromium in DEPS to cc6b1b930d4b5eca06701820dac54fa0f41e8999

* chore: bump chromium in DEPS to 7d1445641ad1032c67f731ba6ff7798f29349ade

* chore: bump chromium in DEPS to 6f7e5e79cefe982ad84a88927565a88db2e592be

* chore: bump chromium in DEPS to bfb25dafff19cb41bf9781331d19ef0be819d1e4

* chore: bump chromium in DEPS to 1a8196b39f0e0cdc4935fd122fff5625d5fab06e

* chore: bump chromium in DEPS to 9a03d8d2bb38ad8c0cbb9550ca81b2f94ff60c15

* chore: bump chromium in DEPS to 4c67f3505dab2d5457adb418cd3270a4f3236fd0

* chore: bump chromium in DEPS to 652394e7626fc1ae895a53fb34c64070494e648e

* chore: bump chromium in DEPS to 07653652c58cc019af7f833bd63eb0c2eceaab5e

* chore: bump chromium in DEPS to 451a1c5fec1fb073a5bae12a033bb342c72c905f

* chore: bump chromium in DEPS to 86cdba00e233899a232868b412b333d08db63478

* chore: bump chromium in DEPS to 7c322faad1aee8abef2330d74aabf09ecf8c11af

* Update patches

* chore: bump chromium in DEPS to d0044fae7efc29eb201cfdd5fdbed77d48aba212

* Replace IsProcessingUserGesture with HasTransientUserActivation

4baa9a6e85

* Fix 10.15 sdk build

0eaa6db358

* Remove CancelPrerender

5eb3329719

* Remove no longer used WebFloatPoint

43ab96ce6b

* Use base::span<const uint8_t> for devtools messages in content/public

21e19401af

* Update renamed header files

* TODO: update with upstream changes

This code needs to be updated to handle the changes made in:
19be6547a9

* chore: bump chromium in DEPS to 82e5a2c6bd33c2e53634a09fbcbc9fcac1e7ff93

* chore: bump chromium in DEPS to 91f877cadd2995201c276e952b3bf2c60b226c64

* chore: bump chromium in DEPS to 43fcd2ab2677a06d38246b42761dc5b40cf87177

* chore: bump chromium in DEPS to e30957dcb710c0977a7ff95b8d3cf65843df12ca

* chore: bump chromium in DEPS to 6a8335a56db12aae2fd06296f82579d804d92217

* chore: bump chromium in DEPS to a4a436cbc28ace88d71752f8f479e59559e54e46

* chore: bump chromium in DEPS to 982bbd0e4b2e1d57d515f384f6483ffc0d7073ad

* chore: bump chromium in DEPS to 92bb7a99f84ffcdf41d4edca57e90b1f0c7c6c8b

* update patches

* add checkout_google_benchmark gclient var

* FIXME: workaround grit bug

* chore: bump chromium in DEPS to d3623fc53615739e6b59340a5d349e4b397cb7c5

* update patches

* Remove color arg from DidChangeThemeColor().

https://chromium-review.googlesource.com/c/chromium/src/+/1982623

* update CreateFileURLLoader with new suffix

CL: https://chromium-review.googlesource.com/c/chromium/src/+/1981414

* add node patch for removal of task API in v8

CL: https://chromium-review.googlesource.com/c/v8/v8/+/1868620

* add disable_secure_dns param for WillCreateURLLoaderFactory

CL: https://chromium-review.googlesource.com/c/chromium/src/+/1888099

* switch to mojo-ified PrintMsg_PrintPreview

CL: https://chromium-review.googlesource.com/c/chromium/src/+/1972307

* chore: bump chromium in DEPS to e7a6d173632660b6aeb9806e9132c34a315331c2

* update missing chrome/browser/ssl:proto dependency after chrome removal

CL: https://chromium-review.googlesource.com/c/chromium/src/+/1986082

* chore: add libvulkan.so to the linux manifest

CL: https://chromium-review.googlesource.com/c/chromium/src/+/1973042

* revert DidChangeThemeColor ternary change due to templates

* match Chrome's mojo-ified implementation in geolocation_permission_context.cc

CL: https://chromium-review.googlesource.com/c/chromium/src/+/1963371

* add vulkan-1.dll to zips

2d6f74c6d4

* add bug link to fixme_grit_conflicts.patch

* Introduce device.mojom.DeviceService

https://chromium-review.googlesource.com/c/chromium/src/+/1956277

* PDF Compositor rename to Print Compositor

https://chromium-review.googlesource.com/c/chromium/src/+/1981135

* chore: bump chromium_version 00362ea584735b4acf4c5a0e1912d7987f8645ab

* chore: update patches

* Use a virtual base class to provide GetWidget().

https://chromium-review.googlesource.com/c/chromium/src/+/1996948

* [base] Remove usage of base::CurrentThread

https://chromium-review.googlesource.com/c/chromium/src/+/1962019

* chore: gn format

* Revert "ci: Use Visual Studio Build Tools instead of VS Studio (#21771)"

This reverts commit 9c1310dadc.

* fix: trigger resize when iframe requests fullscreen

* fix: Locking scheme registry is not necessary

https://chromium-review.googlesource.com/c/chromium/src/+/1973198

* chore: bump chromium f707f1d6d428f84cf14b64bc2ca74372e25c6ce7

* chore: update patches

* ui/base/clipboard: Remove redundant ANSI format functions

https://chromium-review.googlesource.com/c/chromium/src/+/1992015

* [base] Prepare //chrome for Value::GetList() switch

https://chromium-review.googlesource.com/c/chromium/src/+/1962255

Co-authored-by: John Kleinschmidt <jkleinsc@github.com>
Co-authored-by: loc <andy@slack-corp.com>
Co-authored-by: Jeremy Apthorp <nornagon@nornagon.net>
Co-authored-by: Robo <hop2deep@gmail.com>
2020-01-17 10:41:52 -08:00

316 lines
11 KiB
C++

// Copyright (c) 2019 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "shell/browser/net/asar/asar_url_loader.h"
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "base/strings/stringprintf.h"
#include "base/task/post_task.h"
#include "content/public/browser/file_url_loader.h"
#include "mojo/public/cpp/bindings/receiver.h"
#include "mojo/public/cpp/bindings/remote.h"
#include "mojo/public/cpp/system/data_pipe_producer.h"
#include "mojo/public/cpp/system/file_data_source.h"
#include "net/base/filename_util.h"
#include "net/base/mime_sniffer.h"
#include "net/base/mime_util.h"
#include "net/http/http_byte_range.h"
#include "net/http/http_util.h"
#include "services/network/public/mojom/url_response_head.mojom.h"
#include "shell/common/asar/archive.h"
#include "shell/common/asar/asar_util.h"
namespace asar {
namespace {
net::Error ConvertMojoResultToNetError(MojoResult result) {
switch (result) {
case MOJO_RESULT_OK:
return net::OK;
case MOJO_RESULT_NOT_FOUND:
return net::ERR_FILE_NOT_FOUND;
case MOJO_RESULT_PERMISSION_DENIED:
return net::ERR_ACCESS_DENIED;
case MOJO_RESULT_RESOURCE_EXHAUSTED:
return net::ERR_INSUFFICIENT_RESOURCES;
case MOJO_RESULT_ABORTED:
return net::ERR_ABORTED;
default:
return net::ERR_FAILED;
}
}
constexpr size_t kDefaultFileUrlPipeSize = 65536;
// Because this makes things simpler.
static_assert(kDefaultFileUrlPipeSize >= net::kMaxBytesToSniff,
"Default file data pipe size must be at least as large as a MIME-"
"type sniffing buffer.");
// Modified from the |FileURLLoader| in |file_url_loader_factory.cc|, to serve
// asar files instead of normal files.
class AsarURLLoader : public network::mojom::URLLoader {
public:
static void CreateAndStart(
const network::ResourceRequest& request,
network::mojom::URLLoaderRequest loader,
mojo::PendingRemote<network::mojom::URLLoaderClient> client,
scoped_refptr<net::HttpResponseHeaders> extra_response_headers) {
// Owns itself. Will live as long as its URLLoader and URLLoaderClientPtr
// bindings are alive - essentially until either the client gives up or all
// file data has been sent to it.
auto* asar_url_loader = new AsarURLLoader;
asar_url_loader->Start(request, std::move(loader), std::move(client),
std::move(extra_response_headers));
}
// network::mojom::URLLoader:
void FollowRedirect(const std::vector<std::string>& removed_headers,
const net::HttpRequestHeaders& modified_headers,
const base::Optional<GURL>& new_url) override {}
void SetPriority(net::RequestPriority priority,
int32_t intra_priority_value) override {}
void PauseReadingBodyFromNet() override {}
void ResumeReadingBodyFromNet() override {}
private:
AsarURLLoader() {}
~AsarURLLoader() override = default;
void Start(const network::ResourceRequest& request,
mojo::PendingReceiver<network::mojom::URLLoader> loader,
mojo::PendingRemote<network::mojom::URLLoaderClient> client,
scoped_refptr<net::HttpResponseHeaders> extra_response_headers) {
auto head = network::mojom::URLResponseHead::New();
head->request_start = base::TimeTicks::Now();
head->response_start = base::TimeTicks::Now();
head->headers = extra_response_headers;
base::FilePath path;
if (!net::FileURLToFilePath(request.url, &path)) {
mojo::Remote<network::mojom::URLLoaderClient> client_remote(
std::move(client));
client_remote->OnComplete(
network::URLLoaderCompletionStatus(net::ERR_FAILED));
MaybeDeleteSelf();
return;
}
// Determine whether it is an asar file.
base::FilePath asar_path, relative_path;
if (!GetAsarArchivePath(path, &asar_path, &relative_path)) {
content::CreateFileURLLoaderBypassingSecurityChecks(
request, std::move(loader), std::move(client), nullptr, false,
extra_response_headers);
MaybeDeleteSelf();
return;
}
client_.Bind(std::move(client));
receiver_.Bind(std::move(loader));
receiver_.set_disconnect_handler(base::BindOnce(
&AsarURLLoader::OnConnectionError, base::Unretained(this)));
// Parse asar archive.
std::shared_ptr<Archive> archive = GetOrCreateAsarArchive(asar_path);
Archive::FileInfo info;
if (!archive || !archive->GetFileInfo(relative_path, &info)) {
OnClientComplete(net::ERR_FILE_NOT_FOUND);
return;
}
// For unpacked path, read like normal file.
base::FilePath real_path;
if (info.unpacked) {
archive->CopyFileOut(relative_path, &real_path);
info.offset = 0;
}
mojo::DataPipe pipe(kDefaultFileUrlPipeSize);
if (!pipe.consumer_handle.is_valid()) {
OnClientComplete(net::ERR_FAILED);
return;
}
// Note that while the |Archive| already opens a |base::File|, we still need
// to create a new |base::File| here, as it might be accessed by multiple
// requests at the same time.
base::File file(info.unpacked ? real_path : archive->path(),
base::File::FLAG_OPEN | base::File::FLAG_READ);
auto file_data_source =
std::make_unique<mojo::FileDataSource>(std::move(file));
mojo::DataPipeProducer::DataSource* data_source = file_data_source.get();
std::vector<char> initial_read_buffer(net::kMaxBytesToSniff);
auto read_result =
data_source->Read(info.offset, base::span<char>(initial_read_buffer));
if (read_result.result != MOJO_RESULT_OK) {
OnClientComplete(ConvertMojoResultToNetError(read_result.result));
return;
}
std::string range_header;
net::HttpByteRange byte_range;
if (request.headers.GetHeader(net::HttpRequestHeaders::kRange,
&range_header)) {
// Handle a simple Range header for a single range.
std::vector<net::HttpByteRange> ranges;
bool fail = false;
if (net::HttpUtil::ParseRangeHeader(range_header, &ranges) &&
ranges.size() == 1) {
byte_range = ranges[0];
if (!byte_range.ComputeBounds(info.size))
fail = true;
} else {
fail = true;
}
if (fail) {
OnClientComplete(net::ERR_REQUEST_RANGE_NOT_SATISFIABLE);
return;
}
}
uint64_t first_byte_to_send = 0;
uint64_t total_bytes_to_send = info.size;
if (byte_range.IsValid()) {
first_byte_to_send = byte_range.first_byte_position();
total_bytes_to_send =
byte_range.last_byte_position() - first_byte_to_send + 1;
}
total_bytes_written_ = total_bytes_to_send;
head->content_length = base::saturated_cast<int64_t>(total_bytes_to_send);
if (first_byte_to_send < read_result.bytes_read) {
// Write any data we read for MIME sniffing, constraining by range where
// applicable. This will always fit in the pipe (see assertion near
// |kDefaultFileUrlPipeSize| definition).
uint32_t write_size = std::min(
static_cast<uint32_t>(read_result.bytes_read - first_byte_to_send),
static_cast<uint32_t>(total_bytes_to_send));
const uint32_t expected_write_size = write_size;
MojoResult result = pipe.producer_handle->WriteData(
&initial_read_buffer[first_byte_to_send], &write_size,
MOJO_WRITE_DATA_FLAG_NONE);
if (result != MOJO_RESULT_OK || write_size != expected_write_size) {
OnFileWritten(result);
return;
}
// Discount the bytes we just sent from the total range.
first_byte_to_send = read_result.bytes_read;
total_bytes_to_send -= write_size;
}
if (!net::GetMimeTypeFromFile(path, &head->mime_type)) {
std::string new_type;
net::SniffMimeType(initial_read_buffer.data(), read_result.bytes_read,
request.url, head->mime_type,
net::ForceSniffFileUrlsForHtml::kDisabled, &new_type);
head->mime_type.assign(new_type);
head->did_mime_sniff = true;
}
if (head->headers) {
head->headers->AddHeader(
base::StringPrintf("%s: %s", net::HttpRequestHeaders::kContentType,
head->mime_type.c_str()));
}
client_->OnReceiveResponse(std::move(head));
client_->OnStartLoadingResponseBody(std::move(pipe.consumer_handle));
if (total_bytes_to_send == 0) {
// There's definitely no more data, so we're already done.
OnFileWritten(MOJO_RESULT_OK);
return;
}
// In case of a range request, seek to the appropriate position before
// sending the remaining bytes asynchronously. Under normal conditions
// (i.e., no range request) this Seek is effectively a no-op.
//
// Note that in Electron we also need to add file offset.
file_data_source->SetRange(
first_byte_to_send + info.offset,
first_byte_to_send + info.offset + total_bytes_to_send);
data_producer_ = std::make_unique<mojo::DataPipeProducer>(
std::move(pipe.producer_handle));
data_producer_->Write(
std::move(file_data_source),
base::BindOnce(&AsarURLLoader::OnFileWritten, base::Unretained(this)));
}
void OnConnectionError() {
receiver_.reset();
MaybeDeleteSelf();
}
void OnClientComplete(net::Error net_error) {
client_->OnComplete(network::URLLoaderCompletionStatus(net_error));
client_.reset();
MaybeDeleteSelf();
}
void MaybeDeleteSelf() {
if (!receiver_.is_bound() && !client_.is_bound())
delete this;
}
void OnFileWritten(MojoResult result) {
// All the data has been written now. Close the data pipe. The consumer will
// be notified that there will be no more data to read from now.
data_producer_.reset();
if (result == MOJO_RESULT_OK) {
network::URLLoaderCompletionStatus status(net::OK);
status.encoded_data_length = total_bytes_written_;
status.encoded_body_length = total_bytes_written_;
status.decoded_body_length = total_bytes_written_;
client_->OnComplete(status);
} else {
client_->OnComplete(network::URLLoaderCompletionStatus(net::ERR_FAILED));
}
client_.reset();
MaybeDeleteSelf();
}
std::unique_ptr<mojo::DataPipeProducer> data_producer_;
mojo::Receiver<network::mojom::URLLoader> receiver_{this};
mojo::Remote<network::mojom::URLLoaderClient> client_;
// In case of successful loads, this holds the total number of bytes written
// to the response (this may be smaller than the total size of the file when
// a byte range was requested).
// It is used to set some of the URLLoaderCompletionStatus data passed back
// to the URLLoaderClients (eg SimpleURLLoader).
size_t total_bytes_written_ = 0;
DISALLOW_COPY_AND_ASSIGN(AsarURLLoader);
};
} // namespace
void CreateAsarURLLoader(
const network::ResourceRequest& request,
network::mojom::URLLoaderRequest loader,
mojo::PendingRemote<network::mojom::URLLoaderClient> client,
scoped_refptr<net::HttpResponseHeaders> extra_response_headers) {
auto task_runner = base::CreateSequencedTaskRunner(
{base::ThreadPool(), base::MayBlock(), base::TaskPriority::USER_VISIBLE,
base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN});
task_runner->PostTask(
FROM_HERE,
base::BindOnce(&AsarURLLoader::CreateAndStart, request, std::move(loader),
std::move(client), std::move(extra_response_headers)));
}
} // namespace asar