aw: Rendering test harness and end-to-end smoke test
[chromium-blink-merge.git] / content / browser / loader / async_resource_handler.cc
blob51b0a744dc9b7f013c89f2f9b0d998553432581c
1 // Copyright (c) 2012 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.
5 #include "content/browser/loader/async_resource_handler.h"
7 #include <algorithm>
8 #include <vector>
10 #include "base/command_line.h"
11 #include "base/containers/hash_tables.h"
12 #include "base/debug/alias.h"
13 #include "base/logging.h"
14 #include "base/memory/shared_memory.h"
15 #include "base/metrics/histogram.h"
16 #include "base/strings/string_number_conversions.h"
17 #include "base/time/time.h"
18 #include "content/browser/devtools/devtools_netlog_observer.h"
19 #include "content/browser/host_zoom_map_impl.h"
20 #include "content/browser/loader/resource_buffer.h"
21 #include "content/browser/loader/resource_dispatcher_host_impl.h"
22 #include "content/browser/loader/resource_message_filter.h"
23 #include "content/browser/loader/resource_request_info_impl.h"
24 #include "content/browser/resource_context_impl.h"
25 #include "content/common/resource_messages.h"
26 #include "content/common/view_messages.h"
27 #include "content/public/browser/resource_dispatcher_host_delegate.h"
28 #include "content/public/common/resource_response.h"
29 #include "net/base/io_buffer.h"
30 #include "net/base/load_flags.h"
31 #include "net/base/net_log.h"
32 #include "net/base/net_util.h"
33 #include "net/url_request/redirect_info.h"
35 using base::TimeTicks;
37 namespace content {
38 namespace {
40 static int kBufferSize = 1024 * 512;
41 static int kMinAllocationSize = 1024 * 4;
42 static int kMaxAllocationSize = 1024 * 32;
44 void GetNumericArg(const std::string& name, int* result) {
45 const std::string& value =
46 base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(name);
47 if (!value.empty())
48 base::StringToInt(value, result);
51 void InitializeResourceBufferConstants() {
52 static bool did_init = false;
53 if (did_init)
54 return;
55 did_init = true;
57 GetNumericArg("resource-buffer-size", &kBufferSize);
58 GetNumericArg("resource-buffer-min-allocation-size", &kMinAllocationSize);
59 GetNumericArg("resource-buffer-max-allocation-size", &kMaxAllocationSize);
62 int CalcUsedPercentage(int bytes_read, int buffer_size) {
63 double ratio = static_cast<double>(bytes_read) / buffer_size;
64 return static_cast<int>(ratio * 100.0 + 0.5); // Round to nearest integer.
67 } // namespace
69 class DependentIOBuffer : public net::WrappedIOBuffer {
70 public:
71 DependentIOBuffer(ResourceBuffer* backing, char* memory)
72 : net::WrappedIOBuffer(memory),
73 backing_(backing) {
75 private:
76 ~DependentIOBuffer() override {}
77 scoped_refptr<ResourceBuffer> backing_;
80 AsyncResourceHandler::AsyncResourceHandler(
81 net::URLRequest* request,
82 ResourceDispatcherHostImpl* rdh)
83 : ResourceHandler(request),
84 ResourceMessageDelegate(request),
85 rdh_(rdh),
86 pending_data_count_(0),
87 allocation_size_(0),
88 did_defer_(false),
89 has_checked_for_sufficient_resources_(false),
90 sent_received_response_msg_(false),
91 sent_first_data_msg_(false),
92 reported_transfer_size_(0) {
93 InitializeResourceBufferConstants();
96 AsyncResourceHandler::~AsyncResourceHandler() {
97 if (has_checked_for_sufficient_resources_)
98 rdh_->FinishedWithResourcesForRequest(request());
101 bool AsyncResourceHandler::OnMessageReceived(const IPC::Message& message) {
102 bool handled = true;
103 IPC_BEGIN_MESSAGE_MAP(AsyncResourceHandler, message)
104 IPC_MESSAGE_HANDLER(ResourceHostMsg_FollowRedirect, OnFollowRedirect)
105 IPC_MESSAGE_HANDLER(ResourceHostMsg_DataReceived_ACK, OnDataReceivedACK)
106 IPC_MESSAGE_UNHANDLED(handled = false)
107 IPC_END_MESSAGE_MAP()
108 return handled;
111 void AsyncResourceHandler::OnFollowRedirect(int request_id) {
112 if (!request()->status().is_success()) {
113 DVLOG(1) << "OnFollowRedirect for invalid request";
114 return;
117 if (!redirect_start_time_.is_null()) {
118 UMA_HISTOGRAM_TIMES("Net.AsyncResourceHandler_RedirectHopTime",
119 TimeTicks::Now() - redirect_start_time_);
120 // Reset start time.
121 redirect_start_time_ = TimeTicks();
124 ResumeIfDeferred();
127 void AsyncResourceHandler::OnDataReceivedACK(int request_id) {
128 if (pending_data_count_) {
129 --pending_data_count_;
131 buffer_->RecycleLeastRecentlyAllocated();
132 if (buffer_->CanAllocate())
133 ResumeIfDeferred();
137 bool AsyncResourceHandler::OnUploadProgress(uint64 position,
138 uint64 size) {
139 ResourceMessageFilter* filter = GetFilter();
140 if (!filter)
141 return false;
142 return filter->Send(
143 new ResourceMsg_UploadProgress(GetRequestID(), position, size));
146 bool AsyncResourceHandler::OnRequestRedirected(
147 const net::RedirectInfo& redirect_info,
148 ResourceResponse* response,
149 bool* defer) {
150 const ResourceRequestInfoImpl* info = GetRequestInfo();
151 if (!info->filter())
152 return false;
154 redirect_start_time_ = TimeTicks::Now();
156 *defer = did_defer_ = true;
157 OnDefer();
159 if (rdh_->delegate()) {
160 rdh_->delegate()->OnRequestRedirected(
161 redirect_info.new_url, request(), info->GetContext(), response);
164 DevToolsNetLogObserver::PopulateResponseInfo(request(), response);
165 response->head.encoded_data_length = request()->GetTotalReceivedBytes();
166 reported_transfer_size_ = 0;
167 response->head.request_start = request()->creation_time();
168 response->head.response_start = TimeTicks::Now();
169 // TODO(davidben): Is it necessary to pass the new first party URL for
170 // cookies? The only case where it can change is top-level navigation requests
171 // and hopefully those will eventually all be owned by the browser. It's
172 // possible this is still needed while renderer-owned ones exist.
173 return info->filter()->Send(new ResourceMsg_ReceivedRedirect(
174 GetRequestID(), redirect_info, response->head));
177 bool AsyncResourceHandler::OnResponseStarted(ResourceResponse* response,
178 bool* defer) {
179 // For changes to the main frame, inform the renderer of the new URL's
180 // per-host settings before the request actually commits. This way the
181 // renderer will be able to set these precisely at the time the
182 // request commits, avoiding the possibility of e.g. zooming the old content
183 // or of having to layout the new content twice.
185 const ResourceRequestInfoImpl* info = GetRequestInfo();
186 if (!info->filter())
187 return false;
189 if (rdh_->delegate()) {
190 rdh_->delegate()->OnResponseStarted(
191 request(), info->GetContext(), response, info->filter());
194 DevToolsNetLogObserver::PopulateResponseInfo(request(), response);
196 const HostZoomMap* host_zoom_map = info->filter()->GetHostZoomMap();
198 if (info->GetResourceType() == RESOURCE_TYPE_MAIN_FRAME && host_zoom_map) {
199 const GURL& request_url = request()->url();
200 info->filter()->Send(new ViewMsg_SetZoomLevelForLoadingURL(
201 info->GetRouteID(),
202 request_url, host_zoom_map->GetZoomLevelForHostAndScheme(
203 request_url.scheme(),
204 net::GetHostOrSpecFromURL(request_url))));
207 // If the parent handler downloaded the resource to a file, grant the child
208 // read permissions on it.
209 if (!response->head.download_file_path.empty()) {
210 rdh_->RegisterDownloadedTempFile(
211 info->GetChildID(), info->GetRequestID(),
212 response->head.download_file_path);
215 response->head.request_start = request()->creation_time();
216 response->head.response_start = TimeTicks::Now();
217 info->filter()->Send(new ResourceMsg_ReceivedResponse(GetRequestID(),
218 response->head));
219 sent_received_response_msg_ = true;
221 if (request()->response_info().metadata.get()) {
222 std::vector<char> copy(request()->response_info().metadata->data(),
223 request()->response_info().metadata->data() +
224 request()->response_info().metadata->size());
225 info->filter()->Send(new ResourceMsg_ReceivedCachedMetadata(GetRequestID(),
226 copy));
229 return true;
232 bool AsyncResourceHandler::OnWillStart(const GURL& url, bool* defer) {
233 return true;
236 bool AsyncResourceHandler::OnBeforeNetworkStart(const GURL& url, bool* defer) {
237 return true;
240 bool AsyncResourceHandler::OnWillRead(scoped_refptr<net::IOBuffer>* buf,
241 int* buf_size,
242 int min_size) {
243 DCHECK_EQ(-1, min_size);
245 if (!EnsureResourceBufferIsInitialized())
246 return false;
248 DCHECK(buffer_->CanAllocate());
249 char* memory = buffer_->Allocate(&allocation_size_);
250 CHECK(memory);
252 *buf = new DependentIOBuffer(buffer_.get(), memory);
253 *buf_size = allocation_size_;
255 UMA_HISTOGRAM_CUSTOM_COUNTS(
256 "Net.AsyncResourceHandler_SharedIOBuffer_Alloc",
257 *buf_size, 0, kMaxAllocationSize, 100);
258 return true;
261 bool AsyncResourceHandler::OnReadCompleted(int bytes_read, bool* defer) {
262 DCHECK_GE(bytes_read, 0);
264 if (!bytes_read)
265 return true;
267 ResourceMessageFilter* filter = GetFilter();
268 if (!filter)
269 return false;
271 buffer_->ShrinkLastAllocation(bytes_read);
273 UMA_HISTOGRAM_CUSTOM_COUNTS(
274 "Net.AsyncResourceHandler_SharedIOBuffer_Used",
275 bytes_read, 0, kMaxAllocationSize, 100);
276 UMA_HISTOGRAM_PERCENTAGE(
277 "Net.AsyncResourceHandler_SharedIOBuffer_UsedPercentage",
278 CalcUsedPercentage(bytes_read, allocation_size_));
280 if (!sent_first_data_msg_) {
281 base::SharedMemoryHandle handle;
282 int size;
283 if (!buffer_->ShareToProcess(filter->PeerHandle(), &handle, &size))
284 return false;
285 filter->Send(new ResourceMsg_SetDataBuffer(
286 GetRequestID(), handle, size, filter->peer_pid()));
287 sent_first_data_msg_ = true;
290 int data_offset = buffer_->GetLastAllocationOffset();
292 int64_t current_transfer_size = request()->GetTotalReceivedBytes();
293 int encoded_data_length = current_transfer_size - reported_transfer_size_;
294 reported_transfer_size_ = current_transfer_size;
296 filter->Send(new ResourceMsg_DataReceived(
297 GetRequestID(), data_offset, bytes_read, encoded_data_length));
298 ++pending_data_count_;
299 UMA_HISTOGRAM_CUSTOM_COUNTS(
300 "Net.AsyncResourceHandler_PendingDataCount",
301 pending_data_count_, 0, 100, 100);
303 if (!buffer_->CanAllocate()) {
304 UMA_HISTOGRAM_CUSTOM_COUNTS(
305 "Net.AsyncResourceHandler_PendingDataCount_WhenFull",
306 pending_data_count_, 0, 100, 100);
307 *defer = did_defer_ = true;
308 OnDefer();
311 return true;
314 void AsyncResourceHandler::OnDataDownloaded(int bytes_downloaded) {
315 int64_t current_transfer_size = request()->GetTotalReceivedBytes();
316 int encoded_data_length = current_transfer_size - reported_transfer_size_;
317 reported_transfer_size_ = current_transfer_size;
319 ResourceMessageFilter* filter = GetFilter();
320 if (filter) {
321 filter->Send(new ResourceMsg_DataDownloaded(
322 GetRequestID(), bytes_downloaded, encoded_data_length));
326 void AsyncResourceHandler::OnResponseCompleted(
327 const net::URLRequestStatus& status,
328 const std::string& security_info,
329 bool* defer) {
330 const ResourceRequestInfoImpl* info = GetRequestInfo();
331 if (!info->filter())
332 return;
334 // If we crash here, figure out what URL the renderer was requesting.
335 // http://crbug.com/107692
336 char url_buf[128];
337 base::strlcpy(url_buf, request()->url().spec().c_str(), arraysize(url_buf));
338 base::debug::Alias(url_buf);
340 // TODO(gavinp): Remove this CHECK when we figure out the cause of
341 // http://crbug.com/124680 . This check mirrors closely check in
342 // WebURLLoaderImpl::OnCompletedRequest that routes this message to a WebCore
343 // ResourceHandleInternal which asserts on its state and crashes. By crashing
344 // when the message is sent, we should get better crash reports.
345 CHECK(status.status() != net::URLRequestStatus::SUCCESS ||
346 sent_received_response_msg_);
348 int error_code = status.error();
349 bool was_ignored_by_handler = info->WasIgnoredByHandler();
351 DCHECK(status.status() != net::URLRequestStatus::IO_PENDING);
352 // If this check fails, then we're in an inconsistent state because all
353 // requests ignored by the handler should be canceled (which should result in
354 // the ERR_ABORTED error code).
355 DCHECK(!was_ignored_by_handler || error_code == net::ERR_ABORTED);
357 // TODO(mkosiba): Fix up cases where we create a URLRequestStatus
358 // with a status() != SUCCESS and an error_code() == net::OK.
359 if (status.status() == net::URLRequestStatus::CANCELED &&
360 error_code == net::OK) {
361 error_code = net::ERR_ABORTED;
362 } else if (status.status() == net::URLRequestStatus::FAILED &&
363 error_code == net::OK) {
364 error_code = net::ERR_FAILED;
367 ResourceMsg_RequestCompleteData request_complete_data;
368 request_complete_data.error_code = error_code;
369 request_complete_data.was_ignored_by_handler = was_ignored_by_handler;
370 request_complete_data.exists_in_cache = request()->response_info().was_cached;
371 request_complete_data.security_info = security_info;
372 request_complete_data.completion_time = TimeTicks::Now();
373 request_complete_data.encoded_data_length =
374 request()->GetTotalReceivedBytes();
375 info->filter()->Send(
376 new ResourceMsg_RequestComplete(GetRequestID(), request_complete_data));
379 bool AsyncResourceHandler::EnsureResourceBufferIsInitialized() {
380 if (buffer_.get() && buffer_->IsInitialized())
381 return true;
383 if (!has_checked_for_sufficient_resources_) {
384 has_checked_for_sufficient_resources_ = true;
385 if (!rdh_->HasSufficientResourcesForRequest(request())) {
386 controller()->CancelWithError(net::ERR_INSUFFICIENT_RESOURCES);
387 return false;
391 buffer_ = new ResourceBuffer();
392 return buffer_->Initialize(kBufferSize,
393 kMinAllocationSize,
394 kMaxAllocationSize);
397 void AsyncResourceHandler::ResumeIfDeferred() {
398 if (did_defer_) {
399 did_defer_ = false;
400 request()->LogUnblocked();
401 controller()->Resume();
405 void AsyncResourceHandler::OnDefer() {
406 request()->LogBlockedBy("AsyncResourceHandler");
409 } // namespace content