refactor: rename the atom directory to shell

This commit is contained in:
Samuel Attard 2019-06-19 13:43:10 -07:00 committed by Samuel Attard
parent 4575a4aae3
commit d7f07e8a80
631 changed files with 0 additions and 0 deletions

View file

@ -0,0 +1,34 @@
// Copyright (c) 2014 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "atom/browser/net/asar/asar_protocol_handler.h"
#include "atom/browser/net/asar/url_request_asar_job.h"
#include "base/task_runner.h"
#include "net/base/filename_util.h"
#include "net/base/net_errors.h"
namespace asar {
AsarProtocolHandler::AsarProtocolHandler(
const scoped_refptr<base::TaskRunner>& file_task_runner)
: file_task_runner_(file_task_runner) {}
AsarProtocolHandler::~AsarProtocolHandler() {}
net::URLRequestJob* AsarProtocolHandler::MaybeCreateJob(
net::URLRequest* request,
net::NetworkDelegate* network_delegate) const {
base::FilePath full_path;
net::FileURLToFilePath(request->url(), &full_path);
auto* job = new URLRequestAsarJob(request, network_delegate);
job->Initialize(file_task_runner_, full_path);
return job;
}
bool AsarProtocolHandler::IsSafeRedirectTarget(const GURL& location) const {
return false;
}
} // namespace asar

View file

@ -0,0 +1,37 @@
// Copyright (c) 2014 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#ifndef ATOM_BROWSER_NET_ASAR_ASAR_PROTOCOL_HANDLER_H_
#define ATOM_BROWSER_NET_ASAR_ASAR_PROTOCOL_HANDLER_H_
#include "base/memory/ref_counted.h"
#include "net/url_request/url_request_job_factory.h"
namespace base {
class TaskRunner;
}
namespace asar {
class AsarProtocolHandler : public net::URLRequestJobFactory::ProtocolHandler {
public:
explicit AsarProtocolHandler(
const scoped_refptr<base::TaskRunner>& file_task_runner);
~AsarProtocolHandler() override;
// net::URLRequestJobFactory::ProtocolHandler:
net::URLRequestJob* MaybeCreateJob(
net::URLRequest* request,
net::NetworkDelegate* network_delegate) const override;
bool IsSafeRedirectTarget(const GURL& location) const override;
private:
const scoped_refptr<base::TaskRunner> file_task_runner_;
DISALLOW_COPY_AND_ASSIGN(AsarProtocolHandler);
};
} // namespace asar
#endif // ATOM_BROWSER_NET_ASAR_ASAR_PROTOCOL_HANDLER_H_

View file

@ -0,0 +1,300 @@
// 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 "atom/browser/net/asar/asar_url_loader.h"
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "atom/common/asar/archive.h"
#include "atom/common/asar/asar_util.h"
#include "base/strings/stringprintf.h"
#include "base/task/post_task.h"
#include "content/public/browser/file_url_loader.h"
#include "mojo/public/cpp/bindings/strong_binding.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"
namespace asar {
namespace {
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,
network::mojom::URLLoaderClientPtrInfo client_info,
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_info),
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 ProceedWithResponse() override {}
void SetPriority(net::RequestPriority priority,
int32_t intra_priority_value) override {}
void PauseReadingBodyFromNet() override {}
void ResumeReadingBodyFromNet() override {}
private:
AsarURLLoader() : binding_(this) {}
~AsarURLLoader() override = default;
void Start(const network::ResourceRequest& request,
network::mojom::URLLoaderRequest loader,
network::mojom::URLLoaderClientPtrInfo client_info,
scoped_refptr<net::HttpResponseHeaders> extra_response_headers) {
network::ResourceResponseHead head;
head.request_start = base::TimeTicks::Now();
head.response_start = base::TimeTicks::Now();
head.headers = extra_response_headers;
binding_.Bind(std::move(loader));
binding_.set_connection_error_handler(base::BindOnce(
&AsarURLLoader::OnConnectionError, base::Unretained(this)));
client_.Bind(std::move(client_info));
base::FilePath path;
if (!net::FileURLToFilePath(request.url, &path)) {
OnClientComplete(net::ERR_FAILED);
return;
}
// Determine whether it is an asar file.
base::FilePath asar_path, relative_path;
if (!GetAsarArchivePath(path, &asar_path, &relative_path)) {
content::CreateFileURLLoader(request, std::move(loader),
std::move(client_), nullptr, false,
extra_response_headers);
MaybeDeleteSelf();
return;
}
// 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);
// Move cursor to sub-file.
file.Seek(base::File::FROM_BEGIN, info.offset);
// File reading logics are copied from FileURLLoader.
if (!file.IsValid()) {
OnClientComplete(net::FileErrorToNetError(file.error_details()));
return;
}
char initial_read_buffer[net::kMaxBytesToSniff];
int initial_read_result =
file.ReadAtCurrentPos(initial_read_buffer, net::kMaxBytesToSniff);
if (initial_read_result < 0) {
base::File::Error read_error = base::File::GetLastFileError();
DCHECK_NE(base::File::FILE_OK, read_error);
OnClientComplete(net::FileErrorToNetError(read_error));
return;
}
size_t initial_read_size = static_cast<size_t>(initial_read_result);
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;
}
}
size_t first_byte_to_send = 0;
size_t total_bytes_to_send = static_cast<size_t>(info.size);
if (byte_range.IsValid()) {
first_byte_to_send =
static_cast<size_t>(byte_range.first_byte_position());
total_bytes_to_send =
static_cast<size_t>(byte_range.last_byte_position()) -
first_byte_to_send + 1;
}
total_bytes_written_ = static_cast<size_t>(total_bytes_to_send);
head.content_length = base::saturated_cast<int64_t>(total_bytes_to_send);
if (first_byte_to_send < initial_read_size) {
// 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>(initial_read_size - 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 = initial_read_size;
total_bytes_to_send -= write_size;
}
if (!net::GetMimeTypeFromFile(path, &head.mime_type)) {
std::string new_type;
net::SniffMimeType(initial_read_buffer, initial_read_result, 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(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.Seek(base::File::FROM_BEGIN,
static_cast<int64_t>(first_byte_to_send) + info.offset);
data_producer_ = std::make_unique<mojo::FileDataPipeProducer>(
std::move(pipe.producer_handle), nullptr);
data_producer_->WriteFromFile(
std::move(file), total_bytes_to_send,
base::BindOnce(&AsarURLLoader::OnFileWritten, base::Unretained(this)));
}
void OnConnectionError() {
binding_.Close();
MaybeDeleteSelf();
}
void OnClientComplete(net::Error net_error) {
client_->OnComplete(network::URLLoaderCompletionStatus(net_error));
client_.reset();
MaybeDeleteSelf();
}
void MaybeDeleteSelf() {
if (!binding_.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::FileDataPipeProducer> data_producer_;
mojo::Binding<network::mojom::URLLoader> binding_;
network::mojom::URLLoaderClientPtr 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,
network::mojom::URLLoaderClientPtr client,
scoped_refptr<net::HttpResponseHeaders> extra_response_headers) {
auto task_runner = base::CreateSequencedTaskRunnerWithTraits(
{base::MayBlock(), base::TaskPriority::USER_VISIBLE,
base::TaskShutdownBehavior::SKIP_ON_SHUTDOWN});
task_runner->PostTask(
FROM_HERE, base::BindOnce(&AsarURLLoader::CreateAndStart, request,
std::move(loader), client.PassInterface(),
std::move(extra_response_headers)));
}
} // namespace asar

View file

@ -0,0 +1,20 @@
// Copyright (c) 2019 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#ifndef ATOM_BROWSER_NET_ASAR_ASAR_URL_LOADER_H_
#define ATOM_BROWSER_NET_ASAR_ASAR_URL_LOADER_H_
#include "services/network/public/mojom/url_loader.mojom.h"
namespace asar {
void CreateAsarURLLoader(
const network::ResourceRequest& request,
network::mojom::URLLoaderRequest loader,
network::mojom::URLLoaderClientPtr client,
scoped_refptr<net::HttpResponseHeaders> extra_response_headers);
} // namespace asar
#endif // ATOM_BROWSER_NET_ASAR_ASAR_URL_LOADER_H_

View file

@ -0,0 +1,337 @@
// Copyright (c) 2014 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "atom/browser/net/asar/url_request_asar_job.h"
#include <string>
#include <utility>
#include <vector>
#include "atom/common/asar/archive.h"
#include "atom/common/asar/asar_util.h"
#include "atom/common/atom_constants.h"
#include "base/bind.h"
#include "base/files/file_util.h"
#include "base/strings/string_util.h"
#include "base/synchronization/lock.h"
#include "base/task_runner.h"
#include "base/threading/thread_task_runner_handle.h"
#include "net/base/file_stream.h"
#include "net/base/filename_util.h"
#include "net/base/io_buffer.h"
#include "net/base/load_flags.h"
#include "net/base/mime_util.h"
#include "net/base/net_errors.h"
#include "net/filter/gzip_source_stream.h"
#include "net/http/http_util.h"
#include "net/url_request/url_request_status.h"
#if defined(OS_WIN)
#include "base/win/shortcut.h"
#endif
namespace asar {
URLRequestAsarJob::FileMetaInfo::FileMetaInfo() = default;
URLRequestAsarJob::URLRequestAsarJob(net::URLRequest* request,
net::NetworkDelegate* network_delegate)
: net::URLRequestJob(request, network_delegate), weak_ptr_factory_(this) {}
URLRequestAsarJob::~URLRequestAsarJob() {}
void URLRequestAsarJob::Initialize(
const scoped_refptr<base::TaskRunner> file_task_runner,
const base::FilePath& file_path) {
// Determine whether it is an asar file.
base::FilePath asar_path, relative_path;
if (!GetAsarArchivePath(file_path, &asar_path, &relative_path)) {
InitializeFileJob(file_task_runner, file_path);
return;
}
std::shared_ptr<Archive> archive = GetOrCreateAsarArchive(asar_path);
Archive::FileInfo file_info;
if (!archive || !archive->GetFileInfo(relative_path, &file_info)) {
type_ = JobType::kError;
return;
}
if (file_info.unpacked) {
base::FilePath real_path;
archive->CopyFileOut(relative_path, &real_path);
InitializeFileJob(file_task_runner, real_path);
return;
}
InitializeAsarJob(file_task_runner, archive, relative_path, file_info);
}
void URLRequestAsarJob::InitializeAsarJob(
const scoped_refptr<base::TaskRunner> file_task_runner,
std::shared_ptr<Archive> archive,
const base::FilePath& file_path,
const Archive::FileInfo& file_info) {
type_ = JobType::kAsar;
file_task_runner_ = file_task_runner;
stream_.reset(new net::FileStream(file_task_runner_));
archive_ = archive;
file_path_ = file_path;
file_info_ = file_info;
}
void URLRequestAsarJob::InitializeFileJob(
const scoped_refptr<base::TaskRunner> file_task_runner,
const base::FilePath& file_path) {
type_ = JobType::kFile;
file_task_runner_ = file_task_runner;
stream_.reset(new net::FileStream(file_task_runner_));
file_path_ = file_path;
}
void URLRequestAsarJob::Start() {
if (type_ == JobType::kAsar || type_ == JobType::kFile) {
auto* meta_info = new FileMetaInfo();
if (type_ == JobType::kAsar) {
meta_info->file_path = archive_->path();
meta_info->file_exists = true;
meta_info->is_directory = false;
meta_info->file_size = file_info_.size;
}
file_task_runner_->PostTaskAndReply(
FROM_HERE,
base::BindOnce(&URLRequestAsarJob::FetchMetaInfo, file_path_, type_,
base::Unretained(meta_info)),
base::BindOnce(&URLRequestAsarJob::DidFetchMetaInfo,
weak_ptr_factory_.GetWeakPtr(), base::Owned(meta_info)));
} else {
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE, base::BindOnce(&URLRequestAsarJob::DidOpen,
weak_ptr_factory_.GetWeakPtr(),
net::ERR_FILE_NOT_FOUND));
}
}
void URLRequestAsarJob::Kill() {
stream_.reset();
weak_ptr_factory_.InvalidateWeakPtrs();
URLRequestJob::Kill();
}
int URLRequestAsarJob::ReadRawData(net::IOBuffer* dest, int dest_size) {
if (remaining_bytes_ < dest_size)
dest_size = static_cast<int>(remaining_bytes_);
// If we should copy zero bytes because |remaining_bytes_| is zero, short
// circuit here.
if (!dest_size)
return 0;
int rv = stream_->Read(
dest, dest_size,
base::BindOnce(&URLRequestAsarJob::DidRead,
weak_ptr_factory_.GetWeakPtr(), WrapRefCounted(dest)));
if (rv >= 0) {
remaining_bytes_ -= rv;
DCHECK_GE(remaining_bytes_, 0);
}
return rv;
}
bool URLRequestAsarJob::IsRedirectResponse(GURL* location,
int* http_status_code,
bool* insecure_scheme_was_upgraded) {
if (type_ != JobType::kFile)
return false;
#if defined(OS_WIN)
// Follow a Windows shortcut.
// We just resolve .lnk file, ignore others.
if (!base::LowerCaseEqualsASCII(file_path_.Extension(), ".lnk"))
return false;
base::FilePath new_path = file_path_;
bool resolved;
resolved = base::win::ResolveShortcut(new_path, &new_path, NULL);
// If shortcut is not resolved succesfully, do not redirect.
if (!resolved)
return false;
*location = net::FilePathToFileURL(new_path);
*http_status_code = 301;
*insecure_scheme_was_upgraded = false;
return true;
#else
return false;
#endif
}
std::unique_ptr<net::SourceStream> URLRequestAsarJob::SetUpSourceStream() {
std::unique_ptr<net::SourceStream> source =
net::URLRequestJob::SetUpSourceStream();
// Bug 9936 - .svgz files needs to be decompressed.
return base::LowerCaseEqualsASCII(file_path_.Extension(), ".svgz")
? net::GzipSourceStream::Create(std::move(source),
net::SourceStream::TYPE_GZIP)
: std::move(source);
}
bool URLRequestAsarJob::GetMimeType(std::string* mime_type) const {
if (meta_info_.mime_type_result) {
*mime_type = meta_info_.mime_type;
return true;
}
return false;
}
void URLRequestAsarJob::SetExtraRequestHeaders(
const net::HttpRequestHeaders& headers) {
std::string range_header;
if (headers.GetHeader(net::HttpRequestHeaders::kRange, &range_header)) {
// This job only cares about the Range header. This method stashes the value
// for later use in DidOpen(), which is responsible for some of the range
// validation as well. NotifyStartError is not legal to call here since
// the job has not started.
std::vector<net::HttpByteRange> ranges;
if (net::HttpUtil::ParseRangeHeader(range_header, &ranges)) {
if (ranges.size() == 1) {
byte_range_ = ranges[0];
} else {
range_parse_result_ = net::ERR_REQUEST_RANGE_NOT_SATISFIABLE;
}
}
}
}
int URLRequestAsarJob::GetResponseCode() const {
// Request Job gets created only if path exists.
return 200;
}
void URLRequestAsarJob::GetResponseInfo(net::HttpResponseInfo* info) {
std::string status("HTTP/1.1 200 OK");
auto* headers = new net::HttpResponseHeaders(status);
headers->AddHeader(atom::kCORSHeader);
info->headers = headers;
}
void URLRequestAsarJob::FetchMetaInfo(const base::FilePath& file_path,
JobType type,
FileMetaInfo* meta_info) {
if (type == JobType::kFile) {
base::File::Info file_info;
meta_info->file_exists = base::GetFileInfo(file_path, &file_info);
if (meta_info->file_exists) {
meta_info->file_path = file_path;
meta_info->file_size = file_info.size;
meta_info->is_directory = file_info.is_directory;
}
}
// We use GetWellKnownMimeTypeFromExtension() to ensure that configurations
// that may have been set by other programs on a user's machine don't affect
// the mime type returned (in particular, JS should always be
// (application/javascript). See https://crbug.com/797712. Using an accurate
// mime type is necessary at least for modules and sw, which enforce strict
// mime type requirements.
// TODO(deepak1556): Revert this when sw support is removed for file scheme.
base::FilePath::StringType file_extension = file_path.Extension();
if (file_extension.empty()) {
meta_info->mime_type_result = false;
} else {
meta_info->mime_type_result = net::GetWellKnownMimeTypeFromExtension(
file_extension.substr(1), &meta_info->mime_type);
}
}
void URLRequestAsarJob::DidFetchMetaInfo(const FileMetaInfo* meta_info) {
meta_info_ = *meta_info;
if (!meta_info_.file_exists || meta_info_.is_directory) {
DidOpen(net::ERR_FILE_NOT_FOUND);
return;
}
int flags =
base::File::FLAG_OPEN | base::File::FLAG_READ | base::File::FLAG_ASYNC;
int rv = stream_->Open(meta_info_.file_path, flags,
base::BindOnce(&URLRequestAsarJob::DidOpen,
weak_ptr_factory_.GetWeakPtr()));
if (rv != net::ERR_IO_PENDING)
DidOpen(rv);
}
void URLRequestAsarJob::DidOpen(int result) {
if (result != net::OK) {
NotifyStartError(
net::URLRequestStatus(net::URLRequestStatus::FAILED, result));
return;
}
if (range_parse_result_ != net::OK) {
NotifyStartError(net::URLRequestStatus(net::URLRequestStatus::FAILED,
range_parse_result_));
return;
}
int64_t file_size, read_offset;
if (type_ == JobType::kAsar) {
file_size = file_info_.size;
read_offset = file_info_.offset;
} else {
file_size = meta_info_.file_size;
read_offset = 0;
}
if (!byte_range_.ComputeBounds(file_size)) {
NotifyStartError(net::URLRequestStatus(
net::URLRequestStatus::FAILED, net::ERR_REQUEST_RANGE_NOT_SATISFIABLE));
return;
}
remaining_bytes_ =
byte_range_.last_byte_position() - byte_range_.first_byte_position() + 1;
seek_offset_ = byte_range_.first_byte_position() + read_offset;
if (remaining_bytes_ > 0 && seek_offset_ != 0) {
int rv = stream_->Seek(seek_offset_,
base::BindOnce(&URLRequestAsarJob::DidSeek,
weak_ptr_factory_.GetWeakPtr()));
if (rv != net::ERR_IO_PENDING) {
// stream_->Seek() failed, so pass an intentionally erroneous value
// into DidSeek().
DidSeek(-1);
}
} else {
// We didn't need to call stream_->Seek() at all, so we pass to DidSeek()
// the value that would mean seek success. This way we skip the code
// handling seek failure.
DidSeek(seek_offset_);
}
}
void URLRequestAsarJob::DidSeek(int64_t result) {
if (result != seek_offset_) {
NotifyStartError(net::URLRequestStatus(
net::URLRequestStatus::FAILED, net::ERR_REQUEST_RANGE_NOT_SATISFIABLE));
return;
}
set_expected_content_size(remaining_bytes_);
NotifyHeadersComplete();
}
void URLRequestAsarJob::DidRead(scoped_refptr<net::IOBuffer> buf, int result) {
if (result >= 0) {
remaining_bytes_ -= result;
DCHECK_GE(remaining_bytes_, 0);
}
buf = nullptr;
ReadRawDataComplete(result);
}
} // namespace asar

View file

@ -0,0 +1,137 @@
// Copyright (c) 2014 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#ifndef ATOM_BROWSER_NET_ASAR_URL_REQUEST_ASAR_JOB_H_
#define ATOM_BROWSER_NET_ASAR_URL_REQUEST_ASAR_JOB_H_
#include <memory>
#include <string>
#include "atom/browser/net/js_asker.h"
#include "atom/common/asar/archive.h"
#include "base/files/file_path.h"
#include "base/memory/ref_counted.h"
#include "base/memory/weak_ptr.h"
#include "net/http/http_byte_range.h"
#include "net/url_request/url_request_job.h"
namespace base {
class TaskRunner;
}
namespace net {
class FileStream;
}
namespace asar {
// Createa a request job according to the file path.
net::URLRequestJob* CreateJobFromPath(
const base::FilePath& full_path,
net::URLRequest* request,
net::NetworkDelegate* network_delegate,
const scoped_refptr<base::TaskRunner> file_task_runner);
class URLRequestAsarJob : public net::URLRequestJob {
public:
URLRequestAsarJob(net::URLRequest* request,
net::NetworkDelegate* network_delegate);
void Initialize(const scoped_refptr<base::TaskRunner> file_task_runner,
const base::FilePath& file_path);
protected:
~URLRequestAsarJob() override;
void InitializeAsarJob(const scoped_refptr<base::TaskRunner> file_task_runner,
std::shared_ptr<Archive> archive,
const base::FilePath& file_path,
const Archive::FileInfo& file_info);
void InitializeFileJob(const scoped_refptr<base::TaskRunner> file_task_runner,
const base::FilePath& file_path);
// net::URLRequestJob:
void Start() override;
void Kill() override;
int ReadRawData(net::IOBuffer* buf, int buf_size) override;
bool IsRedirectResponse(GURL* location,
int* http_status_code,
bool* insecure_scheme_was_upgraded) override;
std::unique_ptr<net::SourceStream> SetUpSourceStream() override;
bool GetMimeType(std::string* mime_type) const override;
void SetExtraRequestHeaders(const net::HttpRequestHeaders& headers) override;
int GetResponseCode() const override;
void GetResponseInfo(net::HttpResponseInfo* info) override;
private:
// The type of this job.
enum class JobType {
kError,
kAsar,
kFile,
};
// Meta information about the file. It's used as a member in the
// URLRequestFileJob and also passed between threads because disk access is
// necessary to obtain it.
struct FileMetaInfo {
// Size of the file.
int64_t file_size = 0;
// Mime type associated with the file.
std::string mime_type;
// Result returned from GetMimeTypeFromFile(), i.e. flag showing whether
// obtaining of the mime type was successful.
bool mime_type_result = false;
// Flag showing whether the file exists.
bool file_exists = false;
// Flag showing whether the file name actually refers to a directory.
bool is_directory = false;
// Path to the file.
base::FilePath file_path;
FileMetaInfo();
};
// Fetches file info on a background thread.
static void FetchMetaInfo(const base::FilePath& file_path,
JobType type,
FileMetaInfo* meta_info);
// Callback after fetching file info on a background thread.
void DidFetchMetaInfo(const FileMetaInfo* meta_info);
// Callback after opening file on a background thread.
void DidOpen(int result);
// Callback after seeking to the beginning of |byte_range_| in the file
// on a background thread.
void DidSeek(int64_t result);
// Callback after data is asynchronously read from the file into |buf|.
void DidRead(scoped_refptr<net::IOBuffer> buf, int result);
JobType type_ = JobType::kError;
std::shared_ptr<Archive> archive_;
base::FilePath file_path_;
Archive::FileInfo file_info_;
std::unique_ptr<net::FileStream> stream_;
FileMetaInfo meta_info_;
scoped_refptr<base::TaskRunner> file_task_runner_;
net::HttpByteRange byte_range_;
int64_t remaining_bytes_ = 0;
int64_t seek_offset_ = 0;
net::Error range_parse_result_ = net::OK;
base::WeakPtrFactory<URLRequestAsarJob> weak_ptr_factory_;
DISALLOW_COPY_AND_ASSIGN(URLRequestAsarJob);
};
} // namespace asar
#endif // ATOM_BROWSER_NET_ASAR_URL_REQUEST_ASAR_JOB_H_