summaryrefslogtreecommitdiffstats
path: root/storage/browser/blob/blob_url_request_job.cc
blob: deea30027a321abe8f06f4cf5038431685d2a1ea (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
// 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 <algorithm>
#include <limits>
#include <string>
#include <vector>

#include "base/basictypes.h"
#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