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"
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_macros.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
;
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
);
48 base::StringToInt(value
, result
);
51 void InitializeResourceBufferConstants() {
52 static bool did_init
= false;
57 GetNumericArg("resource-buffer-size", &kBufferSize
);
58 GetNumericArg("resource-buffer-min-allocation-size", &kMinAllocationSize
);
59 GetNumericArg("resource-buffer-max-allocation-size", &kMaxAllocationSize
);
64 class DependentIOBuffer
: public net::WrappedIOBuffer
{
66 DependentIOBuffer(ResourceBuffer
* backing
, char* memory
)
67 : net::WrappedIOBuffer(memory
),
71 ~DependentIOBuffer() override
{}
72 scoped_refptr
<ResourceBuffer
> backing_
;
75 AsyncResourceHandler::AsyncResourceHandler(
76 net::URLRequest
* request
,
77 ResourceDispatcherHostImpl
* rdh
)
78 : ResourceHandler(request
),
79 ResourceMessageDelegate(request
),
81 pending_data_count_(0),
84 has_checked_for_sufficient_resources_(false),
85 sent_received_response_msg_(false),
86 sent_first_data_msg_(false),
87 reported_transfer_size_(0) {
88 InitializeResourceBufferConstants();
91 AsyncResourceHandler::~AsyncResourceHandler() {
92 if (has_checked_for_sufficient_resources_
)
93 rdh_
->FinishedWithResourcesForRequest(request());
96 bool AsyncResourceHandler::OnMessageReceived(const IPC::Message
& message
) {
98 IPC_BEGIN_MESSAGE_MAP(AsyncResourceHandler
, message
)
99 IPC_MESSAGE_HANDLER(ResourceHostMsg_FollowRedirect
, OnFollowRedirect
)
100 IPC_MESSAGE_HANDLER(ResourceHostMsg_DataReceived_ACK
, OnDataReceivedACK
)
101 IPC_MESSAGE_UNHANDLED(handled
= false)
102 IPC_END_MESSAGE_MAP()
106 void AsyncResourceHandler::OnFollowRedirect(int request_id
) {
107 if (!request()->status().is_success()) {
108 DVLOG(1) << "OnFollowRedirect for invalid request";
112 if (!redirect_start_time_
.is_null()) {
113 UMA_HISTOGRAM_TIMES("Net.AsyncResourceHandler_RedirectHopTime",
114 TimeTicks::Now() - redirect_start_time_
);
116 redirect_start_time_
= TimeTicks();
122 void AsyncResourceHandler::OnDataReceivedACK(int request_id
) {
123 if (pending_data_count_
) {
124 --pending_data_count_
;
126 buffer_
->RecycleLeastRecentlyAllocated();
127 if (buffer_
->CanAllocate())
132 bool AsyncResourceHandler::OnUploadProgress(uint64 position
,
134 ResourceMessageFilter
* filter
= GetFilter();
138 new ResourceMsg_UploadProgress(GetRequestID(), position
, size
));
141 bool AsyncResourceHandler::OnRequestRedirected(
142 const net::RedirectInfo
& redirect_info
,
143 ResourceResponse
* response
,
145 const ResourceRequestInfoImpl
* info
= GetRequestInfo();
149 redirect_start_time_
= TimeTicks::Now();
151 *defer
= did_defer_
= true;
154 if (rdh_
->delegate()) {
155 rdh_
->delegate()->OnRequestRedirected(
156 redirect_info
.new_url
, request(), info
->GetContext(), response
);
159 DevToolsNetLogObserver::PopulateResponseInfo(request(), response
);
160 response
->head
.encoded_data_length
= request()->GetTotalReceivedBytes();
161 reported_transfer_size_
= 0;
162 response
->head
.request_start
= request()->creation_time();
163 response
->head
.response_start
= TimeTicks::Now();
164 // TODO(davidben): Is it necessary to pass the new first party URL for
165 // cookies? The only case where it can change is top-level navigation requests
166 // and hopefully those will eventually all be owned by the browser. It's
167 // possible this is still needed while renderer-owned ones exist.
168 return info
->filter()->Send(new ResourceMsg_ReceivedRedirect(
169 GetRequestID(), redirect_info
, response
->head
));
172 bool AsyncResourceHandler::OnResponseStarted(ResourceResponse
* response
,
174 // For changes to the main frame, inform the renderer of the new URL's
175 // per-host settings before the request actually commits. This way the
176 // renderer will be able to set these precisely at the time the
177 // request commits, avoiding the possibility of e.g. zooming the old content
178 // or of having to layout the new content twice.
180 const ResourceRequestInfoImpl
* info
= GetRequestInfo();
184 if (rdh_
->delegate()) {
185 rdh_
->delegate()->OnResponseStarted(
186 request(), info
->GetContext(), response
, info
->filter());
189 DevToolsNetLogObserver::PopulateResponseInfo(request(), response
);
191 const HostZoomMapImpl
* host_zoom_map
=
192 static_cast<const HostZoomMapImpl
*>(info
->filter()->GetHostZoomMap());
194 if (info
->GetResourceType() == RESOURCE_TYPE_MAIN_FRAME
&& host_zoom_map
) {
195 const GURL
& request_url
= request()->url();
196 int render_process_id
= info
->GetChildID();
197 int render_view_id
= info
->GetRouteID();
199 double zoom_level
= host_zoom_map
->GetZoomLevelForView(
200 request_url
, render_process_id
, render_view_id
);
202 info
->filter()->Send(new ViewMsg_SetZoomLevelForLoadingURL(
203 render_view_id
, request_url
, zoom_level
));
206 // If the parent handler downloaded the resource to a file, grant the child
207 // read permissions on it.
208 if (!response
->head
.download_file_path
.empty()) {
209 rdh_
->RegisterDownloadedTempFile(
210 info
->GetChildID(), info
->GetRequestID(),
211 response
->head
.download_file_path
);
214 response
->head
.request_start
= request()->creation_time();
215 response
->head
.response_start
= TimeTicks::Now();
216 info
->filter()->Send(new ResourceMsg_ReceivedResponse(GetRequestID(),
218 sent_received_response_msg_
= true;
220 if (request()->response_info().metadata
.get()) {
221 std::vector
<char> copy(request()->response_info().metadata
->data(),
222 request()->response_info().metadata
->data() +
223 request()->response_info().metadata
->size());
224 info
->filter()->Send(new ResourceMsg_ReceivedCachedMetadata(GetRequestID(),
231 bool AsyncResourceHandler::OnWillStart(const GURL
& url
, bool* defer
) {
235 bool AsyncResourceHandler::OnBeforeNetworkStart(const GURL
& url
, bool* defer
) {
239 bool AsyncResourceHandler::OnWillRead(scoped_refptr
<net::IOBuffer
>* buf
,
242 DCHECK_EQ(-1, min_size
);
244 if (!EnsureResourceBufferIsInitialized())
247 DCHECK(buffer_
->CanAllocate());
248 char* memory
= buffer_
->Allocate(&allocation_size_
);
251 *buf
= new DependentIOBuffer(buffer_
.get(), memory
);
252 *buf_size
= allocation_size_
;
257 bool AsyncResourceHandler::OnReadCompleted(int bytes_read
, bool* defer
) {
258 DCHECK_GE(bytes_read
, 0);
263 ResourceMessageFilter
* filter
= GetFilter();
267 buffer_
->ShrinkLastAllocation(bytes_read
);
269 if (!sent_first_data_msg_
) {
270 base::SharedMemoryHandle handle
;
272 if (!buffer_
->ShareToProcess(filter
->PeerHandle(), &handle
, &size
))
274 filter
->Send(new ResourceMsg_SetDataBuffer(
275 GetRequestID(), handle
, size
, filter
->peer_pid()));
276 sent_first_data_msg_
= true;
279 int data_offset
= buffer_
->GetLastAllocationOffset();
281 int64_t current_transfer_size
= request()->GetTotalReceivedBytes();
282 int encoded_data_length
= current_transfer_size
- reported_transfer_size_
;
283 reported_transfer_size_
= current_transfer_size
;
285 filter
->Send(new ResourceMsg_DataReceived(
286 GetRequestID(), data_offset
, bytes_read
, encoded_data_length
));
287 ++pending_data_count_
;
289 if (!buffer_
->CanAllocate()) {
290 *defer
= did_defer_
= true;
297 void AsyncResourceHandler::OnDataDownloaded(int bytes_downloaded
) {
298 int64_t current_transfer_size
= request()->GetTotalReceivedBytes();
299 int encoded_data_length
= current_transfer_size
- reported_transfer_size_
;
300 reported_transfer_size_
= current_transfer_size
;
302 ResourceMessageFilter
* filter
= GetFilter();
304 filter
->Send(new ResourceMsg_DataDownloaded(
305 GetRequestID(), bytes_downloaded
, encoded_data_length
));
309 void AsyncResourceHandler::OnResponseCompleted(
310 const net::URLRequestStatus
& status
,
311 const std::string
& security_info
,
313 const ResourceRequestInfoImpl
* info
= GetRequestInfo();
317 // If we crash here, figure out what URL the renderer was requesting.
318 // http://crbug.com/107692
320 base::strlcpy(url_buf
, request()->url().spec().c_str(), arraysize(url_buf
));
321 base::debug::Alias(url_buf
);
323 // TODO(gavinp): Remove this CHECK when we figure out the cause of
324 // http://crbug.com/124680 . This check mirrors closely check in
325 // WebURLLoaderImpl::OnCompletedRequest that routes this message to a WebCore
326 // ResourceHandleInternal which asserts on its state and crashes. By crashing
327 // when the message is sent, we should get better crash reports.
328 CHECK(status
.status() != net::URLRequestStatus::SUCCESS
||
329 sent_received_response_msg_
);
331 int error_code
= status
.error();
332 bool was_ignored_by_handler
= info
->WasIgnoredByHandler();
334 DCHECK(status
.status() != net::URLRequestStatus::IO_PENDING
);
335 // If this check fails, then we're in an inconsistent state because all
336 // requests ignored by the handler should be canceled (which should result in
337 // the ERR_ABORTED error code).
338 DCHECK(!was_ignored_by_handler
|| error_code
== net::ERR_ABORTED
);
340 // TODO(mkosiba): Fix up cases where we create a URLRequestStatus
341 // with a status() != SUCCESS and an error_code() == net::OK.
342 if (status
.status() == net::URLRequestStatus::CANCELED
&&
343 error_code
== net::OK
) {
344 error_code
= net::ERR_ABORTED
;
345 } else if (status
.status() == net::URLRequestStatus::FAILED
&&
346 error_code
== net::OK
) {
347 error_code
= net::ERR_FAILED
;
350 ResourceMsg_RequestCompleteData request_complete_data
;
351 request_complete_data
.error_code
= error_code
;
352 request_complete_data
.was_ignored_by_handler
= was_ignored_by_handler
;
353 request_complete_data
.exists_in_cache
= request()->response_info().was_cached
;
354 request_complete_data
.security_info
= security_info
;
355 request_complete_data
.completion_time
= TimeTicks::Now();
356 request_complete_data
.encoded_data_length
=
357 request()->GetTotalReceivedBytes();
358 info
->filter()->Send(
359 new ResourceMsg_RequestComplete(GetRequestID(), request_complete_data
));
362 bool AsyncResourceHandler::EnsureResourceBufferIsInitialized() {
363 if (buffer_
.get() && buffer_
->IsInitialized())
366 if (!has_checked_for_sufficient_resources_
) {
367 has_checked_for_sufficient_resources_
= true;
368 if (!rdh_
->HasSufficientResourcesForRequest(request())) {
369 controller()->CancelWithError(net::ERR_INSUFFICIENT_RESOURCES
);
374 buffer_
= new ResourceBuffer();
375 return buffer_
->Initialize(kBufferSize
,
380 void AsyncResourceHandler::ResumeIfDeferred() {
383 request()->LogUnblocked();
384 controller()->Resume();
388 void AsyncResourceHandler::OnDefer() {
389 request()->LogBlockedBy("AsyncResourceHandler");
392 } // namespace content