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/download/download_resource_handler.h"
10 #include "base/logging.h"
11 #include "base/message_loop/message_loop_proxy.h"
12 #include "base/metrics/histogram_macros.h"
13 #include "base/metrics/sparse_histogram.h"
14 #include "base/strings/stringprintf.h"
15 #include "content/browser/byte_stream.h"
16 #include "content/browser/download/download_create_info.h"
17 #include "content/browser/download/download_interrupt_reasons_impl.h"
18 #include "content/browser/download/download_manager_impl.h"
19 #include "content/browser/download/download_request_handle.h"
20 #include "content/browser/download/download_stats.h"
21 #include "content/browser/loader/resource_dispatcher_host_impl.h"
22 #include "content/browser/loader/resource_request_info_impl.h"
23 #include "content/public/browser/browser_thread.h"
24 #include "content/public/browser/download_interrupt_reasons.h"
25 #include "content/public/browser/download_item.h"
26 #include "content/public/browser/download_manager_delegate.h"
27 #include "content/public/browser/navigation_entry.h"
28 #include "content/public/browser/power_save_blocker.h"
29 #include "content/public/browser/web_contents.h"
30 #include "content/public/common/resource_response.h"
31 #include "net/base/io_buffer.h"
32 #include "net/base/net_errors.h"
33 #include "net/http/http_response_headers.h"
34 #include "net/http/http_status_code.h"
35 #include "net/url_request/url_request_context.h"
39 struct DownloadResourceHandler::DownloadTabInfo
{
41 GURL tab_referrer_url
;
46 void CallStartedCBOnUIThread(
47 const DownloadUrlParameters::OnStartedCallback
& started_cb
,
49 DownloadInterruptReason interrupt_reason
) {
50 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
52 if (started_cb
.is_null())
54 started_cb
.Run(item
, interrupt_reason
);
57 // Static function in order to prevent any accidental accesses to
58 // DownloadResourceHandler members from the UI thread.
59 static void StartOnUIThread(
60 scoped_ptr
<DownloadCreateInfo
> info
,
61 scoped_ptr
<DownloadResourceHandler::DownloadTabInfo
> tab_info
,
62 scoped_ptr
<ByteStreamReader
> stream
,
63 const DownloadUrlParameters::OnStartedCallback
& started_cb
) {
64 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
66 DownloadManager
* download_manager
= info
->request_handle
.GetDownloadManager();
67 if (!download_manager
) {
68 // NULL in unittests or if the page closed right after starting the
70 if (!started_cb
.is_null())
71 started_cb
.Run(NULL
, DOWNLOAD_INTERRUPT_REASON_USER_CANCELED
);
73 // |stream| gets deleted on non-FILE thread, but it's ok since
74 // we're not using stream_writer_ yet.
79 info
->tab_url
= tab_info
->tab_url
;
80 info
->tab_referrer_url
= tab_info
->tab_referrer_url
;
82 download_manager
->StartDownload(info
.Pass(), stream
.Pass(), started_cb
);
85 void InitializeDownloadTabInfoOnUIThread(
86 const DownloadRequestHandle
& request_handle
,
87 DownloadResourceHandler::DownloadTabInfo
* tab_info
) {
88 DCHECK_CURRENTLY_ON(BrowserThread::UI
);
90 WebContents
* web_contents
= request_handle
.GetWebContents();
92 NavigationEntry
* entry
= web_contents
->GetController().GetVisibleEntry();
94 tab_info
->tab_url
= entry
->GetURL();
95 tab_info
->tab_referrer_url
= entry
->GetReferrer().url
;
100 void DeleteOnUIThread(
101 scoped_ptr
<DownloadResourceHandler::DownloadTabInfo
> tab_info
) {}
105 const int DownloadResourceHandler::kDownloadByteStreamSize
= 100 * 1024;
107 DownloadResourceHandler::DownloadResourceHandler(
109 net::URLRequest
* request
,
110 const DownloadUrlParameters::OnStartedCallback
& started_cb
,
111 scoped_ptr
<DownloadSaveInfo
> save_info
)
112 : ResourceHandler(request
),
114 started_cb_(started_cb
),
115 save_info_(save_info
.Pass()),
116 tab_info_(new DownloadTabInfo()),
117 last_buffer_size_(0),
120 was_deferred_(false),
121 on_response_started_called_(false) {
122 RecordDownloadCount(UNTHROTTLED_COUNT
);
124 // Do UI thread initialization for tab_info_ asap after
125 // DownloadResourceHandler creation since the tab could be navigated
126 // before StartOnUIThread gets called. This is safe because deletion
127 // will occur via PostTask() as well, which will serialized behind this
129 const ResourceRequestInfoImpl
* request_info
= GetRequestInfo();
130 BrowserThread::PostTask(
131 BrowserThread::UI
, FROM_HERE
,
132 base::Bind(&InitializeDownloadTabInfoOnUIThread
,
133 DownloadRequestHandle(AsWeakPtr(), request_info
->GetChildID(),
134 request_info
->GetRouteID(),
135 request_info
->GetRequestID(),
136 request_info
->frame_tree_node_id()),
138 power_save_blocker_
= PowerSaveBlocker::Create(
139 PowerSaveBlocker::kPowerSaveBlockPreventAppSuspension
,
140 PowerSaveBlocker::kReasonOther
, "Download in progress");
143 bool DownloadResourceHandler::OnUploadProgress(uint64 position
,
148 bool DownloadResourceHandler::OnRequestRedirected(
149 const net::RedirectInfo
& redirect_info
,
150 ResourceResponse
* response
,
155 // Send the download creation information to the download thread.
156 bool DownloadResourceHandler::OnResponseStarted(
157 ResourceResponse
* response
,
159 DCHECK_CURRENTLY_ON(BrowserThread::IO
);
160 // There can be only one (call)
161 DCHECK(!on_response_started_called_
);
162 on_response_started_called_
= true;
164 DVLOG(20) << __FUNCTION__
<< "()" << DebugString();
165 download_start_time_
= base::TimeTicks::Now();
167 // If it's a download, we don't want to poison the cache with it.
168 request()->StopCaching();
170 // Lower priority as well, so downloads don't contend for resources
172 request()->SetPriority(net::IDLE
);
174 // If the content-length header is not present (or contains something other
175 // than numbers), the incoming content_length is -1 (unknown size).
176 // Set the content length to 0 to indicate unknown size to DownloadManager.
177 int64 content_length
=
178 response
->head
.content_length
> 0 ? response
->head
.content_length
: 0;
180 const ResourceRequestInfoImpl
* request_info
= GetRequestInfo();
182 // Deleted in DownloadManager.
183 scoped_ptr
<DownloadCreateInfo
> info(
184 new DownloadCreateInfo(base::Time::Now(),
186 request()->net_log(),
187 request_info
->HasUserGesture(),
188 request_info
->GetPageTransition(),
191 // Create the ByteStream for sending data to the download sink.
192 scoped_ptr
<ByteStreamReader
> stream_reader
;
194 base::MessageLoopProxy::current(),
195 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::FILE),
196 kDownloadByteStreamSize
, &stream_writer_
, &stream_reader
);
197 stream_writer_
->RegisterCallback(
198 base::Bind(&DownloadResourceHandler::ResumeRequest
, AsWeakPtr()));
200 info
->download_id
= download_id_
;
201 info
->url_chain
= request()->url_chain();
202 info
->referrer_url
= GURL(request()->referrer());
203 info
->mime_type
= response
->head
.mime_type
;
204 info
->remote_address
= request()->GetSocketAddress().host();
205 request()->GetResponseHeaderByName("content-disposition",
206 &info
->content_disposition
);
207 RecordDownloadMimeType(info
->mime_type
);
208 RecordDownloadContentDisposition(info
->content_disposition
);
210 info
->request_handle
= DownloadRequestHandle(
211 AsWeakPtr(), request_info
->GetChildID(), request_info
->GetRouteID(),
212 request_info
->GetRequestID(), request_info
->frame_tree_node_id());
214 // Get the last modified time and etag.
215 const net::HttpResponseHeaders
* headers
= request()->response_headers();
217 if (headers
->HasStrongValidators()) {
218 // If we don't have strong validators as per RFC 2616 section 13.3.3, then
219 // we neither store nor use them for range requests.
220 if (!headers
->EnumerateHeader(NULL
, "Last-Modified",
221 &info
->last_modified
))
222 info
->last_modified
.clear();
223 if (!headers
->EnumerateHeader(NULL
, "ETag", &info
->etag
))
227 int status
= headers
->response_code();
228 if (2 == status
/ 100 && status
!= net::HTTP_PARTIAL_CONTENT
) {
229 // Success & not range response; if we asked for a range, we didn't
230 // get it--reset the file pointers to reflect that.
231 info
->save_info
->offset
= 0;
232 info
->save_info
->hash_state
= "";
235 if (!headers
->GetMimeType(&info
->original_mime_type
))
236 info
->original_mime_type
.clear();
239 // Blink verifies that the requester of this download is allowed to set a
240 // suggested name for the security origin of the downlaod URL. However, this
241 // assumption doesn't hold if there were cross origin redirects. Therefore,
242 // clear the suggested_name for such requests.
243 if (info
->url_chain
.size() > 1 &&
244 info
->url_chain
.front().GetOrigin() != info
->url_chain
.back().GetOrigin())
245 info
->save_info
->suggested_name
.clear();
247 BrowserThread::PostTask(
248 BrowserThread::UI
, FROM_HERE
,
249 base::Bind(&StartOnUIThread
,
251 base::Passed(&tab_info_
),
252 base::Passed(&stream_reader
),
253 // Pass to StartOnUIThread so that variable
254 // access is always on IO thread but function
255 // is called on UI thread.
257 // Guaranteed to be called in StartOnUIThread
263 void DownloadResourceHandler::CallStartedCB(
265 DownloadInterruptReason interrupt_reason
) {
266 DCHECK_CURRENTLY_ON(BrowserThread::IO
);
267 if (started_cb_
.is_null())
269 BrowserThread::PostTask(
273 &CallStartedCBOnUIThread
, started_cb_
, item
, interrupt_reason
));
277 bool DownloadResourceHandler::OnWillStart(const GURL
& url
, bool* defer
) {
281 bool DownloadResourceHandler::OnBeforeNetworkStart(const GURL
& url
,
286 // Create a new buffer, which will be handed to the download thread for file
287 // writing and deletion.
288 bool DownloadResourceHandler::OnWillRead(scoped_refptr
<net::IOBuffer
>* buf
,
291 DCHECK_CURRENTLY_ON(BrowserThread::IO
);
292 DCHECK(buf
&& buf_size
);
293 DCHECK(!read_buffer_
.get());
295 *buf_size
= min_size
< 0 ? kReadBufSize
: min_size
;
296 last_buffer_size_
= *buf_size
;
297 read_buffer_
= new net::IOBuffer(*buf_size
);
298 *buf
= read_buffer_
.get();
302 // Pass the buffer to the download file writer.
303 bool DownloadResourceHandler::OnReadCompleted(int bytes_read
, bool* defer
) {
304 DCHECK_CURRENTLY_ON(BrowserThread::IO
);
305 DCHECK(read_buffer_
.get());
307 base::TimeTicks
now(base::TimeTicks::Now());
308 if (!last_read_time_
.is_null()) {
309 double seconds_since_last_read
= (now
- last_read_time_
).InSecondsF();
310 if (now
== last_read_time_
)
311 // Use 1/10 ms as a "very small number" so that we avoid
312 // divide-by-zero error and still record a very high potential bandwidth.
313 seconds_since_last_read
= 0.00001;
315 double actual_bandwidth
= (bytes_read
)/seconds_since_last_read
;
316 double potential_bandwidth
= last_buffer_size_
/seconds_since_last_read
;
317 RecordBandwidth(actual_bandwidth
, potential_bandwidth
);
319 last_read_time_
= now
;
323 bytes_read_
+= bytes_read
;
324 DCHECK(read_buffer_
.get());
326 // Take the data ship it down the stream. If the stream is full, pause the
327 // request; the stream callback will resume it.
328 if (!stream_writer_
->Write(read_buffer_
, bytes_read
)) {
330 *defer
= was_deferred_
= true;
331 last_stream_pause_time_
= now
;
334 read_buffer_
= NULL
; // Drop our reference.
336 if (pause_count_
> 0)
337 *defer
= was_deferred_
= true;
342 void DownloadResourceHandler::OnResponseCompleted(
343 const net::URLRequestStatus
& status
,
344 const std::string
& security_info
,
346 DCHECK_CURRENTLY_ON(BrowserThread::IO
);
347 int response_code
= status
.is_success() ? request()->GetResponseCode() : 0;
348 DVLOG(20) << __FUNCTION__
<< "()" << DebugString()
349 << " status.status() = " << status
.status()
350 << " status.error() = " << status
.error()
351 << " response_code = " << response_code
;
353 net::Error error_code
= net::OK
;
354 if (status
.status() == net::URLRequestStatus::FAILED
||
355 // Note cancels as failures too.
356 status
.status() == net::URLRequestStatus::CANCELED
) {
357 error_code
= static_cast<net::Error
>(status
.error()); // Normal case.
358 // Make sure that at least the fact of failure comes through.
359 if (error_code
== net::OK
)
360 error_code
= net::ERR_FAILED
;
363 // ERR_CONTENT_LENGTH_MISMATCH and ERR_INCOMPLETE_CHUNKED_ENCODING are
364 // allowed since a number of servers in the wild close the connection too
365 // early by mistake. Other browsers - IE9, Firefox 11.0, and Safari 5.1.4 -
366 // treat downloads as complete in both cases, so we follow their lead.
367 if (error_code
== net::ERR_CONTENT_LENGTH_MISMATCH
||
368 error_code
== net::ERR_INCOMPLETE_CHUNKED_ENCODING
) {
369 error_code
= net::OK
;
371 DownloadInterruptReason reason
=
372 ConvertNetErrorToInterruptReason(
373 error_code
, DOWNLOAD_INTERRUPT_FROM_NETWORK
);
375 if (status
.status() == net::URLRequestStatus::CANCELED
&&
376 status
.error() == net::ERR_ABORTED
) {
377 // CANCELED + ERR_ABORTED == something outside of the network
378 // stack cancelled the request. There aren't that many things that
379 // could do this to a download request (whose lifetime is separated from
380 // the tab from which it came). We map this to USER_CANCELLED as the
381 // case we know about (system suspend because of laptop close) corresponds
383 // TODO(ahendrickson) -- Find a better set of codes to use here, as
384 // CANCELED/ERR_ABORTED can occur for reasons other than user cancel.
385 if (net::IsCertStatusError(request()->ssl_info().cert_status
))
386 reason
= DOWNLOAD_INTERRUPT_REASON_SERVER_CERT_PROBLEM
;
388 reason
= DOWNLOAD_INTERRUPT_REASON_USER_CANCELED
;
391 if (status
.is_success() &&
392 reason
== DOWNLOAD_INTERRUPT_REASON_NONE
&&
393 request()->response_headers()) {
394 // Handle server's response codes.
395 switch(response_code
) {
396 case -1: // Non-HTTP request.
398 case net::HTTP_CREATED
:
399 case net::HTTP_ACCEPTED
:
400 case net::HTTP_NON_AUTHORITATIVE_INFORMATION
:
401 case net::HTTP_RESET_CONTENT
:
402 case net::HTTP_PARTIAL_CONTENT
:
403 // Expected successful codes.
405 case net::HTTP_NO_CONTENT
:
406 case net::HTTP_NOT_FOUND
:
407 reason
= DOWNLOAD_INTERRUPT_REASON_SERVER_BAD_CONTENT
;
409 case net::HTTP_PRECONDITION_FAILED
:
410 // Failed our 'If-Unmodified-Since' or 'If-Match'; see
411 // download_manager_impl.cc BeginDownload()
412 reason
= DOWNLOAD_INTERRUPT_REASON_SERVER_PRECONDITION
;
414 case net::HTTP_REQUESTED_RANGE_NOT_SATISFIABLE
:
415 // Retry by downloading from the start automatically:
416 // If we haven't received data when we get this error, we won't.
417 reason
= DOWNLOAD_INTERRUPT_REASON_SERVER_NO_RANGE
;
419 case net::HTTP_UNAUTHORIZED
:
420 // Server didn't authorize this request.
421 reason
= DOWNLOAD_INTERRUPT_REASON_SERVER_UNAUTHORIZED
;
423 case net::HTTP_FORBIDDEN
:
424 // Server forbids access to this resource.
425 reason
= DOWNLOAD_INTERRUPT_REASON_SERVER_FORBIDDEN
;
427 default: // All other errors.
428 // Redirection and informational codes should have been handled earlier
430 DCHECK_NE(3, response_code
/ 100);
431 DCHECK_NE(1, response_code
/ 100);
432 reason
= DOWNLOAD_INTERRUPT_REASON_SERVER_FAILED
;
437 std::string accept_ranges
;
438 bool has_strong_validators
= false;
439 if (request()->response_headers()) {
440 request()->response_headers()->EnumerateHeader(
441 NULL
, "Accept-Ranges", &accept_ranges
);
442 has_strong_validators
=
443 request()->response_headers()->HasStrongValidators();
445 RecordAcceptsRanges(accept_ranges
, bytes_read_
, has_strong_validators
);
446 RecordNetworkBlockage(base::TimeTicks::Now() - download_start_time_
,
449 CallStartedCB(NULL
, reason
);
451 // Send the info down the stream. Conditional is in case we get
452 // OnResponseCompleted without OnResponseStarted.
454 stream_writer_
->Close(reason
);
456 // If the error mapped to something unknown, record it so that
457 // we can drill down.
458 if (reason
== DOWNLOAD_INTERRUPT_REASON_NETWORK_FAILED
) {
459 UMA_HISTOGRAM_SPARSE_SLOWLY("Download.MapErrorNetworkFailed",
460 std::abs(status
.error()));
463 stream_writer_
.reset(); // We no longer need the stream.
467 void DownloadResourceHandler::OnDataDownloaded(int bytes_downloaded
) {
471 void DownloadResourceHandler::PauseRequest() {
472 DCHECK_CURRENTLY_ON(BrowserThread::IO
);
477 void DownloadResourceHandler::ResumeRequest() {
478 DCHECK_CURRENTLY_ON(BrowserThread::IO
);
479 DCHECK_LT(0, pause_count_
);
485 if (pause_count_
> 0)
488 was_deferred_
= false;
489 if (!last_stream_pause_time_
.is_null()) {
490 total_pause_time_
+= (base::TimeTicks::Now() - last_stream_pause_time_
);
491 last_stream_pause_time_
= base::TimeTicks();
494 controller()->Resume();
497 void DownloadResourceHandler::CancelRequest() {
498 DCHECK_CURRENTLY_ON(BrowserThread::IO
);
500 const ResourceRequestInfo
* info
= GetRequestInfo();
501 ResourceDispatcherHostImpl::Get()->CancelRequest(
503 info
->GetRequestID());
504 // This object has been deleted.
507 std::string
DownloadResourceHandler::DebugString() const {
508 const ResourceRequestInfo
* info
= GetRequestInfo();
509 return base::StringPrintf("{"
513 " request_id = " "%d"
518 request()->url().spec().c_str() :
521 info
->GetRequestID(),
525 DownloadResourceHandler::~DownloadResourceHandler() {
526 DCHECK_CURRENTLY_ON(BrowserThread::IO
);
528 // This won't do anything if the callback was called before.
529 // If it goes through, it will likely be because OnWillStart() returned
530 // false somewhere in the chain of resource handlers.
531 CallStartedCB(NULL
, DOWNLOAD_INTERRUPT_REASON_NETWORK_FAILED
);
533 // Remove output stream callback if a stream exists.
535 stream_writer_
->RegisterCallback(base::Closure());
537 // tab_info_ must be destroyed on UI thread, since
538 // InitializeDownloadTabInfoOnUIThread might still be using it.
539 if (tab_info_
.get()) {
540 BrowserThread::PostTask(
541 BrowserThread::UI
, FROM_HERE
,
542 base::Bind(&DeleteOnUIThread
, base::Passed(&tab_info_
)));
545 UMA_HISTOGRAM_TIMES("SB2.DownloadDuration",
546 base::TimeTicks::Now() - download_start_time_
);
549 } // namespace content