blob: 783c3866ba55fef0f4015fdec7f8d2940b106350 [file] [log] [blame]
// Copyright (c) 2012 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 "storage/browser/blob/blob_url_request_job.h"
#include <stdint.h>
#include <algorithm>
#include <limits>
#include <string>
#include <vector>
#include "base/bind.h"
#include "base/compiler_specific.h"
#include "base/files/file_util_proxy.h"
#include "base/format_macros.h"
#include "base/message_loop/message_loop.h"
#include "base/numerics/safe_conversions.h"
#include "base/stl_util.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/stringprintf.h"
#include "base/trace_event/trace_event.h"
#include "net/base/io_buffer.h"
#include "net/base/net_errors.h"
#include "net/disk_cache/disk_cache.h"
#include "net/http/http_request_headers.h"
#include "net/http/http_response_headers.h"
#include "net/http/http_response_info.h"
#include "net/http/http_util.h"
#include "net/url_request/url_request.h"
#include "net/url_request/url_request_context.h"
#include "net/url_request/url_request_error_job.h"
#include "net/url_request/url_request_status.h"
#include "storage/browser/blob/blob_data_handle.h"
#include "storage/browser/blob/blob_reader.h"
#include "storage/browser/fileapi/file_stream_reader.h"
#include "storage/browser/fileapi/file_system_context.h"
#include "storage/browser/fileapi/file_system_url.h"
#include "storage/common/data_element.h"
namespace storage {
BlobURLRequestJob::BlobURLRequestJob(
net::URLRequest* request,
net::NetworkDelegate* network_delegate,
BlobDataHandle* blob_handle,
FileSystemContext* file_system_context,
base::SingleThreadTaskRunner* file_task_runner)
: net::URLRequestJob(request, network_delegate),
error_(false),
byte_range_set_(false),
weak_factory_(this) {
TRACE_EVENT_ASYNC_BEGIN1("Blob", "BlobRequest", this, "uuid",
blob_handle ? blob_handle->uuid() : "NotFound");
DCHECK(file_task_runner);
if (blob_handle) {
blob_handle_.reset(new BlobDataHandle(*blob_handle));
blob_reader_ =
blob_handle_->CreateReader(file_system_context, file_task_runner);
}
}
void BlobURLRequestJob::Start() {
// Continue asynchronously.
base::MessageLoop::current()->PostTask(
FROM_HERE,
base::Bind(&BlobURLRequestJob::DidStart, weak_factory_.GetWeakPtr()));
}
void BlobURLRequestJob::Kill() {
if (blob_reader_) {
blob_reader_->Kill();
}
net::URLRequestJob::Kill();
weak_factory_.InvalidateWeakPtrs();
}
int BlobURLRequestJob::ReadRawData(net::IOBuffer* dest, int dest_size) {
TRACE_EVENT_ASYNC_BEGIN1("Blob", "BlobRequest::ReadRawData", this, "uuid",
blob_handle_ ? blob_handle_->uuid() : "NotFound");
DCHECK_NE(dest_size, 0);
// Bail out immediately if we encounter an error. This happens if a previous
// ReadRawData signalled an error to its caller but the caller called
// ReadRawData again anyway.
if (error_)
return 0;
int bytes_read = 0;
BlobReader::Status read_status =
blob_reader_->Read(dest, dest_size, &bytes_read,
base::Bind(&BlobURLRequestJob::DidReadRawData,
weak_factory_.GetWeakPtr()));
switch (read_status) {
case BlobReader::Status::NET_ERROR:
TRACE_EVENT_ASYNC_END1("Blob", "BlobRequest::ReadRawData", this, "uuid",
blob_handle_ ? blob_handle_->uuid() : "NotFound");
return blob_reader_->net_error();
case BlobReader::Status::IO_PENDING:
return net::ERR_IO_PENDING;
case BlobReader::Status::DONE:
TRACE_EVENT_ASYNC_END1("Blob", "BlobRequest::ReadRawData", this, "uuid",
blob_handle_ ? blob_handle_->uuid() : "NotFound");
return bytes_read;
}
NOTREACHED();
return 0;
}
bool BlobURLRequestJob::GetMimeType(std::string* mime_type) const {
if (!response_info_)
return false;
return response_info_->headers->GetMimeType(mime_type);
}
void BlobURLRequestJob::GetResponseInfo(net::HttpResponseInfo* info) {
if (response_info_)
*info = *response_info_;
}
int BlobURLRequestJob::GetResponseCode() const {
if (!response_info_)
return -1;
return response_info_->headers->response_code();
}
void BlobURLRequestJob::SetExtraRequestHeaders(
const net::HttpRequestHeaders& headers) {
std::string range_header;
if (headers.GetHeader(net::HttpRequestHeaders::kRange, &range_header)) {
// We only care about "Range" header here.
std::vector<net::HttpByteRange> ranges;
if (net::HttpUtil::ParseRangeHeader(range_header, &ranges)) {
if (ranges.size() == 1) {
byte_range_set_ = true;
byte_range_ = ranges[0];
} else {
// We don't support multiple range requests in one single URL request,
// because we need to do multipart encoding here.
// TODO(jianli): Support multipart byte range requests.
NotifyFailure(net::ERR_REQUEST_RANGE_NOT_SATISFIABLE);
}
}
}
}
BlobURLRequestJob::~BlobURLRequestJob() {
TRACE_EVENT_ASYNC_END1("Blob", "BlobRequest", this, "uuid",
blob_handle_ ? blob_handle_->uuid() : "NotFound");
}
void BlobURLRequestJob::DidStart() {
error_ = false;
// We only support GET request per the spec.
if (request()->method() != "GET") {
NotifyFailure(net::ERR_METHOD_NOT_SUPPORTED);
return;
}
// If the blob data is not present, bail out.
if (!blob_handle_) {
NotifyFailure(net::ERR_FILE_NOT_FOUND);
return;
}
TRACE_EVENT_ASYNC_BEGIN1("Blob", "BlobRequest::CountSize", this, "uuid",
blob_handle_->uuid());
BlobReader::Status size_status = blob_reader_->CalculateSize(base::Bind(
&BlobURLRequestJob::DidCalculateSize, weak_factory_.GetWeakPtr()));
switch (size_status) {
case BlobReader::Status::NET_ERROR:
NotifyFailure(blob_reader_->net_error());
return;
case BlobReader::Status::IO_PENDING:
SetStatus(net::URLRequestStatus(net::URLRequestStatus::IO_PENDING, 0));
return;
case BlobReader::Status::DONE:
DidCalculateSize(net::OK);
return;
}
}
void BlobURLRequestJob::DidCalculateSize(int result) {
TRACE_EVENT_ASYNC_END1("Blob", "BlobRequest::CountSize", this, "uuid",
blob_handle_->uuid());
// Clear the IO_PENDING status
SetStatus(net::URLRequestStatus());
if (result != net::OK) {
NotifyFailure(result);
return;
}
// Apply the range requirement.
if (!byte_range_.ComputeBounds(blob_reader_->total_size())) {
NotifyFailure(net::ERR_REQUEST_RANGE_NOT_SATISFIABLE);
return;
}
DCHECK_LE(byte_range_.first_byte_position(),
byte_range_.last_byte_position() + 1);
uint64_t length = base::checked_cast<uint64_t>(
byte_range_.last_byte_position() - byte_range_.first_byte_position() + 1);
if (byte_range_set_)
blob_reader_->SetReadRange(byte_range_.first_byte_position(), length);
net::HttpStatusCode status_code = net::HTTP_OK;
if (byte_range_set_ && byte_range_.IsValid())
status_code = net::HTTP_PARTIAL_CONTENT;
HeadersCompleted(status_code);
}
void BlobURLRequestJob::DidReadRawData(int result) {
TRACE_EVENT_ASYNC_END1("Blob", "BlobRequest::ReadRawData", this, "uuid",
blob_handle_ ? blob_handle_->uuid() : "NotFound");
ReadRawDataComplete(result);
}
void BlobURLRequestJob::NotifyFailure(int error_code) {
error_ = true;
// If we already return the headers on success, we can't change the headers
// now. Instead, we just error out.
DCHECK(!response_info_) << "Cannot NotifyFailure after headers.";
net::HttpStatusCode status_code = net::HTTP_INTERNAL_SERVER_ERROR;
switch (error_code) {
case net::ERR_ACCESS_DENIED:
status_code = net::HTTP_FORBIDDEN;
break;
case net::ERR_FILE_NOT_FOUND:
status_code = net::HTTP_NOT_FOUND;
break;
case net::ERR_METHOD_NOT_SUPPORTED:
status_code = net::HTTP_METHOD_NOT_ALLOWED;
break;
case net::ERR_REQUEST_RANGE_NOT_SATISFIABLE:
status_code = net::HTTP_REQUESTED_RANGE_NOT_SATISFIABLE;
break;
case net::ERR_FAILED:
break;
default:
DCHECK(false);
break;
}
HeadersCompleted(status_code);
}
void BlobURLRequestJob::HeadersCompleted(net::HttpStatusCode status_code) {
std::string status("HTTP/1.1 ");
status.append(base::IntToString(status_code));
status.append(" ");
status.append(net::GetHttpReasonPhrase(status_code));
status.append("\0\0", 2);
net::HttpResponseHeaders* headers = new net::HttpResponseHeaders(status);
set_expected_content_size(0);
if (status_code == net::HTTP_OK || status_code == net::HTTP_PARTIAL_CONTENT) {
set_expected_content_size(blob_reader_->remaining_bytes());
std::string content_length_header(net::HttpRequestHeaders::kContentLength);
content_length_header.append(": ");
content_length_header.append(
base::Int64ToString(blob_reader_->remaining_bytes()));
headers->AddHeader(content_length_header);
if (status_code == net::HTTP_PARTIAL_CONTENT) {
DCHECK(byte_range_set_);
DCHECK(byte_range_.IsValid());
std::string content_range_header(net::HttpResponseHeaders::kContentRange);
content_range_header.append(": bytes ");
content_range_header.append(base::StringPrintf(
"%" PRId64 "-%" PRId64, byte_range_.first_byte_position(),
byte_range_.last_byte_position()));
content_range_header.append("/");
content_range_header.append(
base::StringPrintf("%" PRId64, blob_reader_->total_size()));
headers->AddHeader(content_range_header);
}
if (!blob_handle_->content_type().empty()) {
std::string content_type_header(net::HttpRequestHeaders::kContentType);
content_type_header.append(": ");
content_type_header.append(blob_handle_->content_type());
headers->AddHeader(content_type_header);
}
if (!blob_handle_->content_disposition().empty()) {
std::string content_disposition_header("Content-Disposition: ");
content_disposition_header.append(blob_handle_->content_disposition());
headers->AddHeader(content_disposition_header);
}
}
response_info_.reset(new net::HttpResponseInfo());
response_info_->headers = headers;
NotifyHeadersComplete();
}
} // namespace storage