blob: 26bc87409ea51dee46f1cc2a37171f0ed0e36202 [file] [log] [blame]
yhirano72f62272016-08-13 12:50:061// Copyright 2016 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "content/browser/loader/mojo_async_resource_handler.h"
6
7#include <utility>
8
9#include "base/command_line.h"
10#include "base/containers/hash_tables.h"
11#include "base/logging.h"
12#include "base/macros.h"
13#include "base/strings/string_number_conversions.h"
14#include "base/time/time.h"
15#include "content/browser/loader/netlog_observer.h"
16#include "content/browser/loader/resource_dispatcher_host_impl.h"
17#include "content/browser/loader/resource_request_info_impl.h"
18#include "content/common/resource_request_completion_status.h"
yhirano59393702016-11-16 06:10:2419#include "content/public/browser/global_request_id.h"
mmenke39d9eeda2016-11-16 20:47:4020#include "content/public/browser/resource_controller.h"
yhirano72f62272016-08-13 12:50:0621#include "content/public/browser/resource_dispatcher_host_delegate.h"
22#include "content/public/common/resource_response.h"
23#include "mojo/public/c/system/data_pipe.h"
yhirano7153dc472016-11-16 09:42:4624#include "mojo/public/cpp/bindings/message.h"
yhirano72f62272016-08-13 12:50:0625#include "mojo/public/cpp/system/data_pipe.h"
26#include "net/base/io_buffer.h"
27#include "net/base/load_flags.h"
28#include "net/base/mime_sniffer.h"
yhirano72f62272016-08-13 12:50:0629#include "net/url_request/redirect_info.h"
30
31namespace content {
32namespace {
33
34int g_allocation_size = MojoAsyncResourceHandler::kDefaultAllocationSize;
35
36// MimeTypeResourceHandler *implicitly* requires that the buffer size
37// returned from OnWillRead should be larger than certain size.
38// TODO(yhirano): Fix MimeTypeResourceHandler.
39constexpr size_t kMinAllocationSize = 2 * net::kMaxBytesToSniff;
40
41constexpr size_t kMaxChunkSize = 32 * 1024;
42
43void GetNumericArg(const std::string& name, int* result) {
44 const std::string& value =
45 base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(name);
46 if (!value.empty())
47 base::StringToInt(value, result);
48}
49
50void InitializeResourceBufferConstants() {
51 static bool did_init = false;
52 if (did_init)
53 return;
54 did_init = true;
55
56 GetNumericArg("resource-buffer-size", &g_allocation_size);
57}
58
59} // namespace
60
61// This class is for sharing the ownership of a ScopedDataPipeProducerHandle
62// between WriterIOBuffer and MojoAsyncResourceHandler.
63class MojoAsyncResourceHandler::SharedWriter final
64 : public base::RefCountedThreadSafe<SharedWriter> {
65 public:
66 explicit SharedWriter(mojo::ScopedDataPipeProducerHandle writer)
67 : writer_(std::move(writer)) {}
68 mojo::DataPipeProducerHandle writer() { return writer_.get(); }
69
70 private:
71 friend class base::RefCountedThreadSafe<SharedWriter>;
72 ~SharedWriter() {}
73
74 const mojo::ScopedDataPipeProducerHandle writer_;
75
76 DISALLOW_COPY_AND_ASSIGN(SharedWriter);
77};
78
79// This class is a IOBuffer subclass for data gotten from a
80// ScopedDataPipeProducerHandle.
81class MojoAsyncResourceHandler::WriterIOBuffer final
82 : public net::IOBufferWithSize {
83 public:
84 // |data| and |size| should be gotten from |writer| via BeginWriteDataRaw.
85 // They will be accesible via IOBuffer methods. As |writer| is stored in this
86 // instance, |data| will be kept valid as long as the following conditions
87 // hold:
88 // 1. |data| is not invalidated via EndWriteDataRaw.
89 // 2. |this| instance is alive.
90 WriterIOBuffer(scoped_refptr<SharedWriter> writer, void* data, size_t size)
91 : net::IOBufferWithSize(static_cast<char*>(data), size),
92 writer_(std::move(writer)) {}
93
94 private:
95 ~WriterIOBuffer() override {
96 // Avoid deleting |data_| in the IOBuffer destructor.
97 data_ = nullptr;
98 }
99
100 // This member is for keeping the writer alive.
101 scoped_refptr<SharedWriter> writer_;
102
103 DISALLOW_COPY_AND_ASSIGN(WriterIOBuffer);
104};
105
106MojoAsyncResourceHandler::MojoAsyncResourceHandler(
107 net::URLRequest* request,
108 ResourceDispatcherHostImpl* rdh,
yhiranofe95d9b2016-11-07 04:17:47109 mojom::URLLoaderAssociatedRequest mojo_request,
110 mojom::URLLoaderClientAssociatedPtr url_loader_client)
yhirano72f62272016-08-13 12:50:06111 : ResourceHandler(request),
112 rdh_(rdh),
113 binding_(this, std::move(mojo_request)),
yhiranobbc904d02016-11-26 05:59:26114 url_loader_client_(std::move(url_loader_client)),
115 weak_factory_(this) {
yhirano72f62272016-08-13 12:50:06116 DCHECK(url_loader_client_);
117 InitializeResourceBufferConstants();
yhirano59393702016-11-16 06:10:24118 // This unretained pointer is safe, because |binding_| is owned by |this| and
119 // the callback will never be called after |this| is destroyed.
120 binding_.set_connection_error_handler(
121 base::Bind(&MojoAsyncResourceHandler::Cancel, base::Unretained(this)));
yhiranobbc904d02016-11-26 05:59:26122
123 GetRequestInfo()->set_on_transfer(base::Bind(
124 &MojoAsyncResourceHandler::OnTransfer, weak_factory_.GetWeakPtr()));
yhirano72f62272016-08-13 12:50:06125}
126
127MojoAsyncResourceHandler::~MojoAsyncResourceHandler() {
128 if (has_checked_for_sufficient_resources_)
129 rdh_->FinishedWithResourcesForRequest(request());
130}
131
132bool MojoAsyncResourceHandler::OnRequestRedirected(
133 const net::RedirectInfo& redirect_info,
134 ResourceResponse* response,
135 bool* defer) {
yhirano7153dc472016-11-16 09:42:46136 // Unlike OnResponseStarted, OnRequestRedirected will NOT be preceded by
137 // OnWillRead.
138 DCHECK(!shared_writer_);
139
140 *defer = true;
141 request()->LogBlockedBy("MojoAsyncResourceHandler");
142 did_defer_on_redirect_ = true;
143
144 NetLogObserver::PopulateResponseInfo(request(), response);
145 response->head.encoded_data_length = request()->GetTotalReceivedBytes();
146 response->head.request_start = request()->creation_time();
147 response->head.response_start = base::TimeTicks::Now();
148 // TODO(davidben): Is it necessary to pass the new first party URL for
149 // cookies? The only case where it can change is top-level navigation requests
150 // and hopefully those will eventually all be owned by the browser. It's
151 // possible this is still needed while renderer-owned ones exist.
152 url_loader_client_->OnReceiveRedirect(redirect_info, response->head);
153 return true;
yhirano72f62272016-08-13 12:50:06154}
155
156bool MojoAsyncResourceHandler::OnResponseStarted(ResourceResponse* response,
157 bool* defer) {
158 const ResourceRequestInfoImpl* info = GetRequestInfo();
159
160 if (rdh_->delegate()) {
161 rdh_->delegate()->OnResponseStarted(request(), info->GetContext(),
162 response);
163 }
164
165 NetLogObserver::PopulateResponseInfo(request(), response);
166
167 response->head.request_start = request()->creation_time();
168 response->head.response_start = base::TimeTicks::Now();
169 sent_received_response_message_ = true;
170 url_loader_client_->OnReceiveResponse(response->head);
171 return true;
172}
173
174bool MojoAsyncResourceHandler::OnWillStart(const GURL& url, bool* defer) {
175 return true;
176}
177
178bool MojoAsyncResourceHandler::OnWillRead(scoped_refptr<net::IOBuffer>* buf,
179 int* buf_size,
180 int min_size) {
181 DCHECK_EQ(-1, min_size);
182
183 if (!CheckForSufficientResource())
184 return false;
185
186 if (!shared_writer_) {
187 MojoCreateDataPipeOptions options;
188 options.struct_size = sizeof(MojoCreateDataPipeOptions);
189 options.flags = MOJO_CREATE_DATA_PIPE_OPTIONS_FLAG_NONE;
190 options.element_num_bytes = 1;
191 options.capacity_num_bytes = g_allocation_size;
192 mojo::DataPipe data_pipe(options);
193
194 url_loader_client_->OnStartLoadingResponseBody(
195 std::move(data_pipe.consumer_handle));
196 if (!data_pipe.producer_handle.is_valid())
197 return false;
198
199 shared_writer_ = new SharedWriter(std::move(data_pipe.producer_handle));
200 handle_watcher_.Start(shared_writer_->writer(), MOJO_HANDLE_SIGNAL_WRITABLE,
201 base::Bind(&MojoAsyncResourceHandler::OnWritable,
202 base::Unretained(this)));
203
204 bool defer = false;
205 scoped_refptr<net::IOBufferWithSize> buffer;
206 if (!AllocateWriterIOBuffer(&buffer, &defer))
207 return false;
208 if (!defer) {
209 if (static_cast<size_t>(buffer->size()) >= kMinAllocationSize) {
210 *buf = buffer_ = buffer;
211 *buf_size = buffer_->size();
212 return true;
213 }
214
215 // The allocated buffer is too small.
216 if (EndWrite(0) != MOJO_RESULT_OK)
217 return false;
218 }
219 DCHECK(!is_using_io_buffer_not_from_writer_);
220 is_using_io_buffer_not_from_writer_ = true;
221 buffer_ = new net::IOBufferWithSize(kMinAllocationSize);
222 }
223
224 DCHECK_EQ(0u, buffer_offset_);
225 *buf = buffer_;
226 *buf_size = buffer_->size();
227 return true;
228}
229
230bool MojoAsyncResourceHandler::OnReadCompleted(int bytes_read, bool* defer) {
231 DCHECK_GE(bytes_read, 0);
232 DCHECK(buffer_);
233
234 if (!bytes_read)
235 return true;
236
237 if (is_using_io_buffer_not_from_writer_) {
238 // Couldn't allocate a buffer on the data pipe in OnWillRead.
239 DCHECK_EQ(0u, buffer_bytes_read_);
240 buffer_bytes_read_ = bytes_read;
241 if (!CopyReadDataToDataPipe(defer))
242 return false;
yhirano7153dc472016-11-16 09:42:46243 if (*defer) {
244 request()->LogBlockedBy("MojoAsyncResourceHandler");
245 did_defer_on_writing_ = true;
246 }
yhirano72f62272016-08-13 12:50:06247 return true;
248 }
249
250 if (EndWrite(bytes_read) != MOJO_RESULT_OK)
251 return false;
252 // Allocate a buffer for the next OnWillRead call here, because OnWillRead
253 // doesn't have |defer| parameter.
254 if (!AllocateWriterIOBuffer(&buffer_, defer))
255 return false;
yhirano7153dc472016-11-16 09:42:46256 if (*defer) {
257 request()->LogBlockedBy("MojoAsyncResourceHandler");
258 did_defer_on_writing_ = true;
259 }
yhirano72f62272016-08-13 12:50:06260 return true;
261}
262
263void MojoAsyncResourceHandler::OnDataDownloaded(int bytes_downloaded) {
tzik6e20b742016-11-08 09:14:12264 int64_t total_received_bytes = request()->GetTotalReceivedBytes();
265 int64_t bytes_to_report =
266 total_received_bytes - reported_total_received_bytes_;
267 reported_total_received_bytes_ = total_received_bytes;
268 DCHECK_LE(0, bytes_to_report);
269
270 url_loader_client_->OnDataDownloaded(bytes_downloaded, bytes_to_report);
yhirano72f62272016-08-13 12:50:06271}
272
273void MojoAsyncResourceHandler::FollowRedirect() {
yhirano7153dc472016-11-16 09:42:46274 if (!request()->status().is_success()) {
275 DVLOG(1) << "FollowRedirect for invalid request";
276 return;
277 }
278 if (!did_defer_on_redirect_) {
279 DVLOG(1) << "Malformed FollowRedirect request";
280 ReportBadMessage("Malformed FollowRedirect request");
281 return;
282 }
283
284 DCHECK(!did_defer_on_writing_);
285 did_defer_on_redirect_ = false;
286 request()->LogUnblocked();
287 controller()->Resume();
yhirano72f62272016-08-13 12:50:06288}
289
yhirano7153dc472016-11-16 09:42:46290void MojoAsyncResourceHandler::OnWritableForTesting() {
291 OnWritable(MOJO_RESULT_OK);
yhirano72f62272016-08-13 12:50:06292}
293
294void MojoAsyncResourceHandler::SetAllocationSizeForTesting(size_t size) {
295 g_allocation_size = size;
296}
297
298MojoResult MojoAsyncResourceHandler::BeginWrite(void** data,
299 uint32_t* available) {
300 MojoResult result = mojo::BeginWriteDataRaw(
301 shared_writer_->writer(), data, available, MOJO_WRITE_DATA_FLAG_NONE);
302 if (result == MOJO_RESULT_OK)
303 *available = std::min(*available, static_cast<uint32_t>(kMaxChunkSize));
304 return result;
305}
306
307MojoResult MojoAsyncResourceHandler::EndWrite(uint32_t written) {
308 return mojo::EndWriteDataRaw(shared_writer_->writer(), written);
309}
310
311void MojoAsyncResourceHandler::OnResponseCompleted(
312 const net::URLRequestStatus& status,
yhirano72f62272016-08-13 12:50:06313 bool* defer) {
314 shared_writer_ = nullptr;
315 buffer_ = nullptr;
316 handle_watcher_.Cancel();
317
318 const ResourceRequestInfoImpl* info = GetRequestInfo();
319
320 // TODO(gavinp): Remove this CHECK when we figure out the cause of
321 // http://crbug.com/124680 . This check mirrors closely check in
322 // WebURLLoaderImpl::OnCompletedRequest that routes this message to a WebCore
323 // ResourceHandleInternal which asserts on its state and crashes. By crashing
324 // when the message is sent, we should get better crash reports.
325 CHECK(status.status() != net::URLRequestStatus::SUCCESS ||
326 sent_received_response_message_);
327
328 int error_code = status.error();
329 bool was_ignored_by_handler = info->WasIgnoredByHandler();
330
331 DCHECK_NE(status.status(), net::URLRequestStatus::IO_PENDING);
332 // If this check fails, then we're in an inconsistent state because all
333 // requests ignored by the handler should be canceled (which should result in
334 // the ERR_ABORTED error code).
335 DCHECK(!was_ignored_by_handler || error_code == net::ERR_ABORTED);
336
337 ResourceRequestCompletionStatus request_complete_data;
338 request_complete_data.error_code = error_code;
339 request_complete_data.was_ignored_by_handler = was_ignored_by_handler;
340 request_complete_data.exists_in_cache = request()->response_info().was_cached;
yhirano72f62272016-08-13 12:50:06341 request_complete_data.completion_time = base::TimeTicks::Now();
342 request_complete_data.encoded_data_length =
343 request()->GetTotalReceivedBytes();
344
345 url_loader_client_->OnComplete(request_complete_data);
346}
347
348bool MojoAsyncResourceHandler::CopyReadDataToDataPipe(bool* defer) {
349 while (true) {
350 scoped_refptr<net::IOBufferWithSize> dest;
351 if (!AllocateWriterIOBuffer(&dest, defer))
352 return false;
353 if (*defer)
354 return true;
355 if (buffer_bytes_read_ == 0) {
356 // All bytes are copied. Save the buffer for the next OnWillRead call.
357 buffer_ = std::move(dest);
358 return true;
359 }
360
361 size_t copied_size =
362 std::min(buffer_bytes_read_, static_cast<size_t>(dest->size()));
363 memcpy(dest->data(), buffer_->data() + buffer_offset_, copied_size);
364 buffer_offset_ += copied_size;
365 buffer_bytes_read_ -= copied_size;
366 if (EndWrite(copied_size) != MOJO_RESULT_OK)
367 return false;
368
369 if (buffer_bytes_read_ == 0) {
370 // All bytes are copied.
371 buffer_offset_ = 0;
372 is_using_io_buffer_not_from_writer_ = false;
373 }
374 }
375}
376
377bool MojoAsyncResourceHandler::AllocateWriterIOBuffer(
378 scoped_refptr<net::IOBufferWithSize>* buf,
379 bool* defer) {
380 void* data = nullptr;
381 uint32_t available = 0;
382 MojoResult result = BeginWrite(&data, &available);
383 if (result == MOJO_RESULT_SHOULD_WAIT) {
384 *defer = true;
385 return true;
386 }
387 if (result != MOJO_RESULT_OK)
388 return false;
389 *buf = new WriterIOBuffer(shared_writer_, data, available);
390 return true;
391}
392
yhirano72f62272016-08-13 12:50:06393bool MojoAsyncResourceHandler::CheckForSufficientResource() {
394 if (has_checked_for_sufficient_resources_)
395 return true;
396 has_checked_for_sufficient_resources_ = true;
397
398 if (rdh_->HasSufficientResourcesForRequest(request()))
399 return true;
400
401 controller()->CancelWithError(net::ERR_INSUFFICIENT_RESOURCES);
402 return false;
403}
404
yhirano7153dc472016-11-16 09:42:46405void MojoAsyncResourceHandler::OnWritable(MojoResult result) {
406 if (!did_defer_on_writing_)
407 return;
408 DCHECK(!did_defer_on_redirect_);
409 did_defer_on_writing_ = false;
410
411 if (is_using_io_buffer_not_from_writer_) {
412 // |buffer_| is set to a net::IOBufferWithSize. Write the buffer contents
413 // to the data pipe.
414 DCHECK_GT(buffer_bytes_read_, 0u);
415 if (!CopyReadDataToDataPipe(&did_defer_on_writing_)) {
416 controller()->CancelWithError(net::ERR_FAILED);
417 return;
418 }
419 } else {
420 // Allocate a buffer for the next OnWillRead call here.
421 if (!AllocateWriterIOBuffer(&buffer_, &did_defer_on_writing_)) {
422 controller()->CancelWithError(net::ERR_FAILED);
423 return;
424 }
425 }
426
427 if (did_defer_on_writing_) {
428 // Continue waiting.
429 return;
430 }
431 request()->LogUnblocked();
432 controller()->Resume();
yhirano72f62272016-08-13 12:50:06433}
434
yhirano59393702016-11-16 06:10:24435void MojoAsyncResourceHandler::Cancel() {
436 const ResourceRequestInfoImpl* info = GetRequestInfo();
437 ResourceDispatcherHostImpl::Get()->CancelRequestFromRenderer(
438 GlobalRequestID(info->GetChildID(), info->GetRequestID()));
439}
440
yhirano7153dc472016-11-16 09:42:46441void MojoAsyncResourceHandler::ReportBadMessage(const std::string& error) {
442 mojo::ReportBadMessage(error);
443}
444
yhiranobbc904d02016-11-26 05:59:26445void MojoAsyncResourceHandler::OnTransfer(
446 mojom::URLLoaderAssociatedRequest mojo_request,
447 mojom::URLLoaderClientAssociatedPtr url_loader_client) {
448 binding_.Unbind();
449 binding_.Bind(std::move(mojo_request));
450 binding_.set_connection_error_handler(
451 base::Bind(&MojoAsyncResourceHandler::Cancel, base::Unretained(this)));
452 url_loader_client_ = std::move(url_loader_client);
453}
454
yhirano72f62272016-08-13 12:50:06455} // namespace content