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.h"
13 #include "base/metrics/stats_counters.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(BrowserThread::CurrentlyOn(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 DownloadResourceHandler::DownloadTabInfo* tab_info,
62 scoped_ptr<ByteStreamReader> stream,
63 const DownloadUrlParameters::OnStartedCallback& started_cb) {
64 DCHECK(BrowserThread::CurrentlyOn(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(BrowserThread::CurrentlyOn(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;
102 const int DownloadResourceHandler::kDownloadByteStreamSize = 100 * 1024;
104 DownloadResourceHandler::DownloadResourceHandler(
106 net::URLRequest* request,
107 const DownloadUrlParameters::OnStartedCallback& started_cb,
108 scoped_ptr<DownloadSaveInfo> save_info)
109 : ResourceHandler(request),
111 started_cb_(started_cb),
112 save_info_(save_info.Pass()),
113 last_buffer_size_(0),
116 was_deferred_(false),
117 on_response_started_called_(false) {
118 RecordDownloadCount(UNTHROTTLED_COUNT);
120 // Do UI thread initialization asap after DownloadResourceHandler creation
121 // since the tab could be navigated before StartOnUIThread gets called.
122 const ResourceRequestInfoImpl* request_info = GetRequestInfo();
123 tab_info_ = new DownloadTabInfo();
124 BrowserThread::PostTask(
127 base::Bind(&InitializeDownloadTabInfoOnUIThread,
128 DownloadRequestHandle(AsWeakPtr(),
129 request_info->GetChildID(),
130 request_info->GetRouteID(),
131 request_info->GetRequestID()),
133 power_save_blocker_ = PowerSaveBlocker::Create(
134 PowerSaveBlocker::kPowerSaveBlockPreventAppSuspension,
135 "Download in progress");
138 bool DownloadResourceHandler::OnUploadProgress(int request_id,
144 bool DownloadResourceHandler::OnRequestRedirected(
147 ResourceResponse* response,
149 // We treat a download as a main frame load, and thus update the policy URL
151 request()->set_first_party_for_cookies(url);
155 // Send the download creation information to the download thread.
156 bool DownloadResourceHandler::OnResponseStarted(
158 ResourceResponse* response,
160 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
161 // There can be only one (call)
162 DCHECK(!on_response_started_called_);
163 on_response_started_called_ = true;
165 VLOG(20) << __FUNCTION__ << "()" << DebugString()
166 << " request_id = " << request_id;
167 download_start_time_ = base::TimeTicks::Now();
169 // If it's a download, we don't want to poison the cache with it.
170 request()->StopCaching();
172 // Lower priority as well, so downloads don't contend for resources
174 request()->SetPriority(net::IDLE);
176 // If the content-length header is not present (or contains something other
177 // than numbers), the incoming content_length is -1 (unknown size).
178 // Set the content length to 0 to indicate unknown size to DownloadManager.
179 int64 content_length =
180 response->head.content_length > 0 ? response->head.content_length : 0;
182 const ResourceRequestInfoImpl* request_info = GetRequestInfo();
184 // Deleted in DownloadManager.
185 scoped_ptr<DownloadCreateInfo> info(
186 new DownloadCreateInfo(base::Time::Now(),
188 request()->net_log(),
189 request_info->HasUserGesture(),
190 request_info->GetPageTransition(),
193 // Create the ByteStream for sending data to the download sink.
194 scoped_ptr<ByteStreamReader> stream_reader;
196 base::MessageLoopProxy::current(),
197 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::FILE),
198 kDownloadByteStreamSize, &stream_writer_, &stream_reader);
199 stream_writer_->RegisterCallback(
200 base::Bind(&DownloadResourceHandler::ResumeRequest, AsWeakPtr()));
202 info->download_id = download_id_;
203 info->url_chain = request()->url_chain();
204 info->referrer_url = GURL(request()->referrer());
205 info->mime_type = response->head.mime_type;
206 info->remote_address = request()->GetSocketAddress().host();
207 request()->GetResponseHeaderByName("content-disposition",
208 &info->content_disposition);
209 RecordDownloadMimeType(info->mime_type);
210 RecordDownloadContentDisposition(info->content_disposition);
212 info->request_handle =
213 DownloadRequestHandle(AsWeakPtr(), request_info->GetChildID(),
214 request_info->GetRouteID(),
215 request_info->GetRequestID());
217 // Get the last modified time and etag.
218 const net::HttpResponseHeaders* headers = request()->response_headers();
220 if (headers->HasStrongValidators()) {
221 // If we don't have strong validators as per RFC 2616 section 13.3.3, then
222 // we neither store nor use them for range requests.
223 if (!headers->EnumerateHeader(NULL, "Last-Modified",
224 &info->last_modified))
225 info->last_modified.clear();
226 if (!headers->EnumerateHeader(NULL, "ETag", &info->etag))
230 int status = headers->response_code();
231 if (2 == status / 100 && status != net::HTTP_PARTIAL_CONTENT) {
232 // Success & not range response; if we asked for a range, we didn't
233 // get it--reset the file pointers to reflect that.
234 info->save_info->offset = 0;
235 info->save_info->hash_state = "";
238 if (!headers->GetMimeType(&info->original_mime_type))
239 info->original_mime_type.clear();
242 // Blink verifies that the requester of this download is allowed to set a
243 // suggested name for the security origin of the downlaod URL. However, this
244 // assumption doesn't hold if there were cross origin redirects. Therefore,
245 // clear the suggested_name for such requests.
246 if (info->url_chain.size() > 1 &&
247 info->url_chain.front().GetOrigin() != info->url_chain.back().GetOrigin())
248 info->save_info->suggested_name.clear();
250 BrowserThread::PostTask(
251 BrowserThread::UI, FROM_HERE,
252 base::Bind(&StartOnUIThread,
254 base::Owned(tab_info_),
255 base::Passed(&stream_reader),
256 // Pass to StartOnUIThread so that variable
257 // access is always on IO thread but function
258 // is called on UI thread.
260 // Now owned by the task that was just posted.
262 // Guaranteed to be called in StartOnUIThread
268 void DownloadResourceHandler::CallStartedCB(
270 DownloadInterruptReason interrupt_reason) {
271 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
272 if (started_cb_.is_null())
274 BrowserThread::PostTask(
278 &CallStartedCBOnUIThread, started_cb_, item, interrupt_reason));
282 bool DownloadResourceHandler::OnWillStart(int request_id,
288 bool DownloadResourceHandler::OnBeforeNetworkStart(int request_id,
294 // Create a new buffer, which will be handed to the download thread for file
295 // writing and deletion.
296 bool DownloadResourceHandler::OnWillRead(int request_id,
297 scoped_refptr<net::IOBuffer>* buf,
300 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
301 DCHECK(buf && buf_size);
302 DCHECK(!read_buffer_.get());
304 *buf_size = min_size < 0 ? kReadBufSize : min_size;
305 last_buffer_size_ = *buf_size;
306 read_buffer_ = new net::IOBuffer(*buf_size);
307 *buf = read_buffer_.get();
311 // Pass the buffer to the download file writer.
312 bool DownloadResourceHandler::OnReadCompleted(int request_id, int bytes_read,
314 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
315 DCHECK(read_buffer_.get());
317 base::TimeTicks now(base::TimeTicks::Now());
318 if (!last_read_time_.is_null()) {
319 double seconds_since_last_read = (now - last_read_time_).InSecondsF();
320 if (now == last_read_time_)
321 // Use 1/10 ms as a "very small number" so that we avoid
322 // divide-by-zero error and still record a very high potential bandwidth.
323 seconds_since_last_read = 0.00001;
325 double actual_bandwidth = (bytes_read)/seconds_since_last_read;
326 double potential_bandwidth = last_buffer_size_/seconds_since_last_read;
327 RecordBandwidth(actual_bandwidth, potential_bandwidth);
329 last_read_time_ = now;
333 bytes_read_ += bytes_read;
334 DCHECK(read_buffer_.get());
336 // Take the data ship it down the stream. If the stream is full, pause the
337 // request; the stream callback will resume it.
338 if (!stream_writer_->Write(read_buffer_, bytes_read)) {
340 *defer = was_deferred_ = true;
341 last_stream_pause_time_ = now;
344 read_buffer_ = NULL; // Drop our reference.
346 if (pause_count_ > 0)
347 *defer = was_deferred_ = true;
352 void DownloadResourceHandler::OnResponseCompleted(
354 const net::URLRequestStatus& status,
355 const std::string& security_info,
357 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
358 int response_code = status.is_success() ? request()->GetResponseCode() : 0;
359 VLOG(20) << __FUNCTION__ << "()" << DebugString()
360 << " request_id = " << request_id
361 << " status.status() = " << status.status()
362 << " status.error() = " << status.error()
363 << " response_code = " << response_code;
365 net::Error error_code = net::OK;
366 if (status.status() == net::URLRequestStatus::FAILED ||
367 // Note cancels as failures too.
368 status.status() == net::URLRequestStatus::CANCELED) {
369 error_code = static_cast<net::Error>(status.error()); // Normal case.
370 // Make sure that at least the fact of failure comes through.
371 if (error_code == net::OK)
372 error_code = net::ERR_FAILED;
375 // ERR_CONTENT_LENGTH_MISMATCH and ERR_INCOMPLETE_CHUNKED_ENCODING are
376 // allowed since a number of servers in the wild close the connection too
377 // early by mistake. Other browsers - IE9, Firefox 11.0, and Safari 5.1.4 -
378 // treat downloads as complete in both cases, so we follow their lead.
379 if (error_code == net::ERR_CONTENT_LENGTH_MISMATCH ||
380 error_code == net::ERR_INCOMPLETE_CHUNKED_ENCODING) {
381 error_code = net::OK;
383 DownloadInterruptReason reason =
384 ConvertNetErrorToInterruptReason(
385 error_code, DOWNLOAD_INTERRUPT_FROM_NETWORK);
387 if (status.status() == net::URLRequestStatus::CANCELED &&
388 status.error() == net::ERR_ABORTED) {
389 // CANCELED + ERR_ABORTED == something outside of the network
390 // stack cancelled the request. There aren't that many things that
391 // could do this to a download request (whose lifetime is separated from
392 // the tab from which it came). We map this to USER_CANCELLED as the
393 // case we know about (system suspend because of laptop close) corresponds
395 // TODO(ahendrickson) -- Find a better set of codes to use here, as
396 // CANCELED/ERR_ABORTED can occur for reasons other than user cancel.
397 reason = DOWNLOAD_INTERRUPT_REASON_USER_CANCELED;
400 if (status.is_success() &&
401 reason == DOWNLOAD_INTERRUPT_REASON_NONE &&
402 request()->response_headers()) {
403 // Handle server's response codes.
404 switch(response_code) {
405 case -1: // Non-HTTP request.
407 case net::HTTP_CREATED:
408 case net::HTTP_ACCEPTED:
409 case net::HTTP_NON_AUTHORITATIVE_INFORMATION:
410 case net::HTTP_RESET_CONTENT:
411 case net::HTTP_PARTIAL_CONTENT:
412 // Expected successful codes.
414 case net::HTTP_NO_CONTENT:
415 case net::HTTP_NOT_FOUND:
416 reason = DOWNLOAD_INTERRUPT_REASON_SERVER_BAD_CONTENT;
418 case net::HTTP_PRECONDITION_FAILED:
419 // Failed our 'If-Unmodified-Since' or 'If-Match'; see
420 // download_manager_impl.cc BeginDownload()
421 reason = DOWNLOAD_INTERRUPT_REASON_SERVER_PRECONDITION;
423 case net::HTTP_REQUESTED_RANGE_NOT_SATISFIABLE:
424 // Retry by downloading from the start automatically:
425 // If we haven't received data when we get this error, we won't.
426 reason = DOWNLOAD_INTERRUPT_REASON_SERVER_NO_RANGE;
428 default: // All other errors.
429 // Redirection and informational codes should have been handled earlier
431 DCHECK_NE(3, response_code / 100);
432 DCHECK_NE(1, response_code / 100);
433 reason = DOWNLOAD_INTERRUPT_REASON_SERVER_FAILED;
438 std::string accept_ranges;
439 bool has_strong_validators = false;
440 if (request()->response_headers()) {
441 request()->response_headers()->EnumerateHeader(
442 NULL, "Accept-Ranges", &accept_ranges);
443 has_strong_validators =
444 request()->response_headers()->HasStrongValidators();
446 RecordAcceptsRanges(accept_ranges, bytes_read_, has_strong_validators);
447 RecordNetworkBlockage(base::TimeTicks::Now() - download_start_time_,
450 CallStartedCB(NULL, reason);
452 // Send the info down the stream. Conditional is in case we get
453 // OnResponseCompleted without OnResponseStarted.
455 stream_writer_->Close(reason);
457 // If the error mapped to something unknown, record it so that
458 // we can drill down.
459 if (reason == DOWNLOAD_INTERRUPT_REASON_NETWORK_FAILED) {
460 UMA_HISTOGRAM_CUSTOM_ENUMERATION("Download.MapErrorNetworkFailed",
461 std::abs(status.error()),
462 net::GetAllErrorCodesForUma());
465 stream_writer_.reset(); // We no longer need the stream.
469 void DownloadResourceHandler::OnDataDownloaded(
471 int bytes_downloaded) {
475 void DownloadResourceHandler::PauseRequest() {
476 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
481 void DownloadResourceHandler::ResumeRequest() {
482 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
483 DCHECK_LT(0, pause_count_);
489 if (pause_count_ > 0)
492 was_deferred_ = false;
493 if (!last_stream_pause_time_.is_null()) {
494 total_pause_time_ += (base::TimeTicks::Now() - last_stream_pause_time_);
495 last_stream_pause_time_ = base::TimeTicks();
498 controller()->Resume();
501 void DownloadResourceHandler::CancelRequest() {
502 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
504 const ResourceRequestInfo* info = GetRequestInfo();
505 ResourceDispatcherHostImpl::Get()->CancelRequest(
507 info->GetRequestID());
508 // This object has been deleted.
511 std::string DownloadResourceHandler::DebugString() const {
512 const ResourceRequestInfo* info = GetRequestInfo();
513 return base::StringPrintf("{"
517 " request_id = " "%d"
522 request()->url().spec().c_str() :
525 info->GetRequestID(),
529 DownloadResourceHandler::~DownloadResourceHandler() {
530 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
532 // This won't do anything if the callback was called before.
533 // If it goes through, it will likely be because OnWillStart() returned
534 // false somewhere in the chain of resource handlers.
535 CallStartedCB(NULL, DOWNLOAD_INTERRUPT_REASON_NETWORK_FAILED);
537 // Remove output stream callback if a stream exists.
539 stream_writer_->RegisterCallback(base::Closure());
541 // tab_info_ must be destroyed on UI thread, since
542 // InitializeDownloadTabInfoOnUIThread might still be using it.
544 BrowserThread::DeleteSoon(BrowserThread::UI, FROM_HERE, tab_info_);
546 UMA_HISTOGRAM_TIMES("SB2.DownloadDuration",
547 base::TimeTicks::Now() - download_start_time_);
550 } // namespace content