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_util.h"
32 #include "net/log/net_log.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";
115 void AsyncResourceHandler::OnDataReceivedACK(int request_id
) {
116 if (pending_data_count_
) {
117 --pending_data_count_
;
119 buffer_
->RecycleLeastRecentlyAllocated();
120 if (buffer_
->CanAllocate())
125 bool AsyncResourceHandler::OnUploadProgress(uint64 position
,
127 ResourceMessageFilter
* filter
= GetFilter();
131 new ResourceMsg_UploadProgress(GetRequestID(), position
, size
));
134 bool AsyncResourceHandler::OnRequestRedirected(
135 const net::RedirectInfo
& redirect_info
,
136 ResourceResponse
* response
,
138 const ResourceRequestInfoImpl
* info
= GetRequestInfo();
142 *defer
= did_defer_
= true;
145 if (rdh_
->delegate()) {
146 rdh_
->delegate()->OnRequestRedirected(
147 redirect_info
.new_url
, request(), info
->GetContext(), response
);
150 DevToolsNetLogObserver::PopulateResponseInfo(request(), response
);
151 response
->head
.encoded_data_length
= request()->GetTotalReceivedBytes();
152 reported_transfer_size_
= 0;
153 response
->head
.request_start
= request()->creation_time();
154 response
->head
.response_start
= TimeTicks::Now();
155 // TODO(davidben): Is it necessary to pass the new first party URL for
156 // cookies? The only case where it can change is top-level navigation requests
157 // and hopefully those will eventually all be owned by the browser. It's
158 // possible this is still needed while renderer-owned ones exist.
159 return info
->filter()->Send(new ResourceMsg_ReceivedRedirect(
160 GetRequestID(), redirect_info
, response
->head
));
163 bool AsyncResourceHandler::OnResponseStarted(ResourceResponse
* response
,
165 // For changes to the main frame, inform the renderer of the new URL's
166 // per-host settings before the request actually commits. This way the
167 // renderer will be able to set these precisely at the time the
168 // request commits, avoiding the possibility of e.g. zooming the old content
169 // or of having to layout the new content twice.
171 const ResourceRequestInfoImpl
* info
= GetRequestInfo();
175 if (rdh_
->delegate()) {
176 rdh_
->delegate()->OnResponseStarted(
177 request(), info
->GetContext(), response
, info
->filter());
180 DevToolsNetLogObserver::PopulateResponseInfo(request(), response
);
182 const HostZoomMapImpl
* host_zoom_map
=
183 static_cast<const HostZoomMapImpl
*>(info
->filter()->GetHostZoomMap());
185 if (info
->GetResourceType() == RESOURCE_TYPE_MAIN_FRAME
&& host_zoom_map
) {
186 const GURL
& request_url
= request()->url();
187 int render_process_id
= info
->GetChildID();
188 int render_view_id
= info
->GetRouteID();
190 double zoom_level
= host_zoom_map
->GetZoomLevelForView(
191 request_url
, render_process_id
, render_view_id
);
193 info
->filter()->Send(new ViewMsg_SetZoomLevelForLoadingURL(
194 render_view_id
, request_url
, zoom_level
));
197 // If the parent handler downloaded the resource to a file, grant the child
198 // read permissions on it.
199 if (!response
->head
.download_file_path
.empty()) {
200 rdh_
->RegisterDownloadedTempFile(
201 info
->GetChildID(), info
->GetRequestID(),
202 response
->head
.download_file_path
);
205 response
->head
.request_start
= request()->creation_time();
206 response
->head
.response_start
= TimeTicks::Now();
207 info
->filter()->Send(new ResourceMsg_ReceivedResponse(GetRequestID(),
209 sent_received_response_msg_
= true;
211 if (request()->response_info().metadata
.get()) {
212 std::vector
<char> copy(request()->response_info().metadata
->data(),
213 request()->response_info().metadata
->data() +
214 request()->response_info().metadata
->size());
215 info
->filter()->Send(new ResourceMsg_ReceivedCachedMetadata(GetRequestID(),
222 bool AsyncResourceHandler::OnWillStart(const GURL
& url
, bool* defer
) {
226 bool AsyncResourceHandler::OnBeforeNetworkStart(const GURL
& url
, bool* defer
) {
230 bool AsyncResourceHandler::OnWillRead(scoped_refptr
<net::IOBuffer
>* buf
,
233 DCHECK_EQ(-1, min_size
);
235 if (!EnsureResourceBufferIsInitialized())
238 DCHECK(buffer_
->CanAllocate());
239 char* memory
= buffer_
->Allocate(&allocation_size_
);
242 *buf
= new DependentIOBuffer(buffer_
.get(), memory
);
243 *buf_size
= allocation_size_
;
248 bool AsyncResourceHandler::OnReadCompleted(int bytes_read
, bool* defer
) {
249 DCHECK_GE(bytes_read
, 0);
254 ResourceMessageFilter
* filter
= GetFilter();
258 buffer_
->ShrinkLastAllocation(bytes_read
);
260 if (!sent_first_data_msg_
) {
261 base::SharedMemoryHandle handle
;
263 if (!buffer_
->ShareToProcess(filter
->PeerHandle(), &handle
, &size
))
265 filter
->Send(new ResourceMsg_SetDataBuffer(
266 GetRequestID(), handle
, size
, filter
->peer_pid()));
267 sent_first_data_msg_
= true;
270 int data_offset
= buffer_
->GetLastAllocationOffset();
272 int64_t current_transfer_size
= request()->GetTotalReceivedBytes();
273 int encoded_data_length
= current_transfer_size
- reported_transfer_size_
;
274 reported_transfer_size_
= current_transfer_size
;
276 filter
->Send(new ResourceMsg_DataReceived(
277 GetRequestID(), data_offset
, bytes_read
, encoded_data_length
));
278 ++pending_data_count_
;
280 if (!buffer_
->CanAllocate()) {
281 *defer
= did_defer_
= true;
288 void AsyncResourceHandler::OnDataDownloaded(int bytes_downloaded
) {
289 int64_t current_transfer_size
= request()->GetTotalReceivedBytes();
290 int encoded_data_length
= current_transfer_size
- reported_transfer_size_
;
291 reported_transfer_size_
= current_transfer_size
;
293 ResourceMessageFilter
* filter
= GetFilter();
295 filter
->Send(new ResourceMsg_DataDownloaded(
296 GetRequestID(), bytes_downloaded
, encoded_data_length
));
300 void AsyncResourceHandler::OnResponseCompleted(
301 const net::URLRequestStatus
& status
,
302 const std::string
& security_info
,
304 const ResourceRequestInfoImpl
* info
= GetRequestInfo();
308 // If we crash here, figure out what URL the renderer was requesting.
309 // http://crbug.com/107692
311 base::strlcpy(url_buf
, request()->url().spec().c_str(), arraysize(url_buf
));
312 base::debug::Alias(url_buf
);
314 // TODO(gavinp): Remove this CHECK when we figure out the cause of
315 // http://crbug.com/124680 . This check mirrors closely check in
316 // WebURLLoaderImpl::OnCompletedRequest that routes this message to a WebCore
317 // ResourceHandleInternal which asserts on its state and crashes. By crashing
318 // when the message is sent, we should get better crash reports.
319 CHECK(status
.status() != net::URLRequestStatus::SUCCESS
||
320 sent_received_response_msg_
);
322 int error_code
= status
.error();
323 bool was_ignored_by_handler
= info
->WasIgnoredByHandler();
325 DCHECK(status
.status() != net::URLRequestStatus::IO_PENDING
);
326 // If this check fails, then we're in an inconsistent state because all
327 // requests ignored by the handler should be canceled (which should result in
328 // the ERR_ABORTED error code).
329 DCHECK(!was_ignored_by_handler
|| error_code
== net::ERR_ABORTED
);
331 // TODO(mkosiba): Fix up cases where we create a URLRequestStatus
332 // with a status() != SUCCESS and an error_code() == net::OK.
333 if (status
.status() == net::URLRequestStatus::CANCELED
&&
334 error_code
== net::OK
) {
335 error_code
= net::ERR_ABORTED
;
336 } else if (status
.status() == net::URLRequestStatus::FAILED
&&
337 error_code
== net::OK
) {
338 error_code
= net::ERR_FAILED
;
341 ResourceMsg_RequestCompleteData request_complete_data
;
342 request_complete_data
.error_code
= error_code
;
343 request_complete_data
.was_ignored_by_handler
= was_ignored_by_handler
;
344 request_complete_data
.exists_in_cache
= request()->response_info().was_cached
;
345 request_complete_data
.security_info
= security_info
;
346 request_complete_data
.completion_time
= TimeTicks::Now();
347 request_complete_data
.encoded_data_length
=
348 request()->GetTotalReceivedBytes();
349 info
->filter()->Send(
350 new ResourceMsg_RequestComplete(GetRequestID(), request_complete_data
));
353 bool AsyncResourceHandler::EnsureResourceBufferIsInitialized() {
354 if (buffer_
.get() && buffer_
->IsInitialized())
357 if (!has_checked_for_sufficient_resources_
) {
358 has_checked_for_sufficient_resources_
= true;
359 if (!rdh_
->HasSufficientResourcesForRequest(request())) {
360 controller()->CancelWithError(net::ERR_INSUFFICIENT_RESOURCES
);
365 buffer_
= new ResourceBuffer();
366 return buffer_
->Initialize(kBufferSize
,
371 void AsyncResourceHandler::ResumeIfDeferred() {
374 request()->LogUnblocked();
375 controller()->Resume();
379 void AsyncResourceHandler::OnDefer() {
380 request()->LogBlockedBy("AsyncResourceHandler");
383 } // namespace content