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/common/resource_response.h"
28 #include "net/base/io_buffer.h"
29 #include "net/base/net_errors.h"
30 #include "net/http/http_response_headers.h"
31 #include "net/http/http_status_code.h"
32 #include "net/url_request/url_request_context.h"
37 void CallStartedCBOnUIThread(
38 const DownloadUrlParameters::OnStartedCallback& started_cb,
40 DownloadInterruptReason interrupt_reason) {
41 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
43 if (started_cb.is_null())
45 started_cb.Run(item, interrupt_reason);
48 // Static function in order to prevent any accidental accesses to
49 // DownloadResourceHandler members from the UI thread.
50 static void StartOnUIThread(
51 scoped_ptr<DownloadCreateInfo> info,
52 scoped_ptr<ByteStreamReader> stream,
53 const DownloadUrlParameters::OnStartedCallback& started_cb) {
54 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
56 DownloadManager* download_manager = info->request_handle.GetDownloadManager();
57 if (!download_manager) {
58 // NULL in unittests or if the page closed right after starting the
60 if (!started_cb.is_null())
61 started_cb.Run(NULL, DOWNLOAD_INTERRUPT_REASON_USER_CANCELED);
65 download_manager->StartDownload(info.Pass(), stream.Pass(), started_cb);
70 const int DownloadResourceHandler::kDownloadByteStreamSize = 100 * 1024;
72 DownloadResourceHandler::DownloadResourceHandler(
74 net::URLRequest* request,
75 const DownloadUrlParameters::OnStartedCallback& started_cb,
76 scoped_ptr<DownloadSaveInfo> save_info)
77 : ResourceHandler(request),
79 started_cb_(started_cb),
80 save_info_(save_info.Pass()),
85 on_response_started_called_(false) {
86 RecordDownloadCount(UNTHROTTLED_COUNT);
89 bool DownloadResourceHandler::OnUploadProgress(int request_id,
95 bool DownloadResourceHandler::OnRequestRedirected(
98 ResourceResponse* response,
100 // We treat a download as a main frame load, and thus update the policy URL
102 request()->set_first_party_for_cookies(url);
106 // Send the download creation information to the download thread.
107 bool DownloadResourceHandler::OnResponseStarted(
109 ResourceResponse* response,
111 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
112 // There can be only one (call)
113 DCHECK(!on_response_started_called_);
114 on_response_started_called_ = true;
116 VLOG(20) << __FUNCTION__ << "()" << DebugString()
117 << " request_id = " << request_id;
118 download_start_time_ = base::TimeTicks::Now();
120 // If it's a download, we don't want to poison the cache with it.
121 request()->StopCaching();
123 // Lower priority as well, so downloads don't contend for resources
125 request()->SetPriority(net::IDLE);
127 // If the content-length header is not present (or contains something other
128 // than numbers), the incoming content_length is -1 (unknown size).
129 // Set the content length to 0 to indicate unknown size to DownloadManager.
130 int64 content_length =
131 response->head.content_length > 0 ? response->head.content_length : 0;
133 const ResourceRequestInfoImpl* request_info = GetRequestInfo();
135 // Deleted in DownloadManager.
136 scoped_ptr<DownloadCreateInfo> info(
137 new DownloadCreateInfo(base::Time::Now(),
139 request()->net_log(),
140 request_info->HasUserGesture(),
141 request_info->GetPageTransition(),
144 // Create the ByteStream for sending data to the download sink.
145 scoped_ptr<ByteStreamReader> stream_reader;
147 base::MessageLoopProxy::current(),
148 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::FILE),
149 kDownloadByteStreamSize, &stream_writer_, &stream_reader);
150 stream_writer_->RegisterCallback(
151 base::Bind(&DownloadResourceHandler::ResumeRequest, AsWeakPtr()));
153 info->download_id = download_id_;
154 info->url_chain = request()->url_chain();
155 info->referrer_url = GURL(request()->referrer());
156 info->mime_type = response->head.mime_type;
157 info->remote_address = request()->GetSocketAddress().host();
158 request()->GetResponseHeaderByName("content-disposition",
159 &info->content_disposition);
160 RecordDownloadMimeType(info->mime_type);
161 RecordDownloadContentDisposition(info->content_disposition);
163 info->request_handle =
164 DownloadRequestHandle(AsWeakPtr(), request_info->GetChildID(),
165 request_info->GetRouteID(),
166 request_info->GetRequestID());
168 // Get the last modified time and etag.
169 const net::HttpResponseHeaders* headers = request()->response_headers();
171 if (headers->HasStrongValidators()) {
172 // If we don't have strong validators as per RFC 2616 section 13.3.3, then
173 // we neither store nor use them for range requests.
174 if (!headers->EnumerateHeader(NULL, "Last-Modified",
175 &info->last_modified))
176 info->last_modified.clear();
177 if (!headers->EnumerateHeader(NULL, "ETag", &info->etag))
181 int status = headers->response_code();
182 if (2 == status / 100 && status != net::HTTP_PARTIAL_CONTENT) {
183 // Success & not range response; if we asked for a range, we didn't
184 // get it--reset the file pointers to reflect that.
185 info->save_info->offset = 0;
186 info->save_info->hash_state = "";
189 if (!headers->GetMimeType(&info->original_mime_type))
190 info->original_mime_type.clear();
193 BrowserThread::PostTask(
194 BrowserThread::UI, FROM_HERE,
195 base::Bind(&StartOnUIThread,
197 base::Passed(&stream_reader),
198 // Pass to StartOnUIThread so that variable
199 // access is always on IO thread but function
200 // is called on UI thread.
202 // Guaranteed to be called in StartOnUIThread
208 void DownloadResourceHandler::CallStartedCB(
210 DownloadInterruptReason interrupt_reason) {
211 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
212 if (started_cb_.is_null())
214 BrowserThread::PostTask(
218 &CallStartedCBOnUIThread, started_cb_, item, interrupt_reason));
222 bool DownloadResourceHandler::OnWillStart(int request_id,
228 bool DownloadResourceHandler::OnBeforeNetworkStart(int request_id,
234 // Create a new buffer, which will be handed to the download thread for file
235 // writing and deletion.
236 bool DownloadResourceHandler::OnWillRead(int request_id,
237 scoped_refptr<net::IOBuffer>* buf,
240 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
241 DCHECK(buf && buf_size);
242 DCHECK(!read_buffer_.get());
244 *buf_size = min_size < 0 ? kReadBufSize : min_size;
245 last_buffer_size_ = *buf_size;
246 read_buffer_ = new net::IOBuffer(*buf_size);
247 *buf = read_buffer_.get();
251 // Pass the buffer to the download file writer.
252 bool DownloadResourceHandler::OnReadCompleted(int request_id, int bytes_read,
254 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
255 DCHECK(read_buffer_.get());
257 base::TimeTicks now(base::TimeTicks::Now());
258 if (!last_read_time_.is_null()) {
259 double seconds_since_last_read = (now - last_read_time_).InSecondsF();
260 if (now == last_read_time_)
261 // Use 1/10 ms as a "very small number" so that we avoid
262 // divide-by-zero error and still record a very high potential bandwidth.
263 seconds_since_last_read = 0.00001;
265 double actual_bandwidth = (bytes_read)/seconds_since_last_read;
266 double potential_bandwidth = last_buffer_size_/seconds_since_last_read;
267 RecordBandwidth(actual_bandwidth, potential_bandwidth);
269 last_read_time_ = now;
273 bytes_read_ += bytes_read;
274 DCHECK(read_buffer_.get());
276 // Take the data ship it down the stream. If the stream is full, pause the
277 // request; the stream callback will resume it.
278 if (!stream_writer_->Write(read_buffer_, bytes_read)) {
280 *defer = was_deferred_ = true;
281 last_stream_pause_time_ = now;
284 read_buffer_ = NULL; // Drop our reference.
286 if (pause_count_ > 0)
287 *defer = was_deferred_ = true;
292 void DownloadResourceHandler::OnResponseCompleted(
294 const net::URLRequestStatus& status,
295 const std::string& security_info,
297 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
298 int response_code = status.is_success() ? request()->GetResponseCode() : 0;
299 VLOG(20) << __FUNCTION__ << "()" << DebugString()
300 << " request_id = " << request_id
301 << " status.status() = " << status.status()
302 << " status.error() = " << status.error()
303 << " response_code = " << response_code;
305 net::Error error_code = net::OK;
306 if (status.status() == net::URLRequestStatus::FAILED ||
307 // Note cancels as failures too.
308 status.status() == net::URLRequestStatus::CANCELED) {
309 error_code = static_cast<net::Error>(status.error()); // Normal case.
310 // Make sure that at least the fact of failure comes through.
311 if (error_code == net::OK)
312 error_code = net::ERR_FAILED;
315 // ERR_CONTENT_LENGTH_MISMATCH and ERR_INCOMPLETE_CHUNKED_ENCODING are
316 // allowed since a number of servers in the wild close the connection too
317 // early by mistake. Other browsers - IE9, Firefox 11.0, and Safari 5.1.4 -
318 // treat downloads as complete in both cases, so we follow their lead.
319 if (error_code == net::ERR_CONTENT_LENGTH_MISMATCH ||
320 error_code == net::ERR_INCOMPLETE_CHUNKED_ENCODING) {
321 error_code = net::OK;
323 DownloadInterruptReason reason =
324 ConvertNetErrorToInterruptReason(
325 error_code, DOWNLOAD_INTERRUPT_FROM_NETWORK);
327 if (status.status() == net::URLRequestStatus::CANCELED &&
328 status.error() == net::ERR_ABORTED) {
329 // CANCELED + ERR_ABORTED == something outside of the network
330 // stack cancelled the request. There aren't that many things that
331 // could do this to a download request (whose lifetime is separated from
332 // the tab from which it came). We map this to USER_CANCELLED as the
333 // case we know about (system suspend because of laptop close) corresponds
335 // TODO(ahendrickson) -- Find a better set of codes to use here, as
336 // CANCELED/ERR_ABORTED can occur for reasons other than user cancel.
337 reason = DOWNLOAD_INTERRUPT_REASON_USER_CANCELED;
340 if (status.is_success() &&
341 reason == DOWNLOAD_INTERRUPT_REASON_NONE &&
342 request()->response_headers()) {
343 // Handle server's response codes.
344 switch(response_code) {
345 case -1: // Non-HTTP request.
347 case net::HTTP_CREATED:
348 case net::HTTP_ACCEPTED:
349 case net::HTTP_NON_AUTHORITATIVE_INFORMATION:
350 case net::HTTP_RESET_CONTENT:
351 case net::HTTP_PARTIAL_CONTENT:
352 // Expected successful codes.
354 case net::HTTP_NO_CONTENT:
355 case net::HTTP_NOT_FOUND:
356 reason = DOWNLOAD_INTERRUPT_REASON_SERVER_BAD_CONTENT;
358 case net::HTTP_PRECONDITION_FAILED:
359 // Failed our 'If-Unmodified-Since' or 'If-Match'; see
360 // download_manager_impl.cc BeginDownload()
361 reason = DOWNLOAD_INTERRUPT_REASON_SERVER_PRECONDITION;
363 case net::HTTP_REQUESTED_RANGE_NOT_SATISFIABLE:
364 // Retry by downloading from the start automatically:
365 // If we haven't received data when we get this error, we won't.
366 reason = DOWNLOAD_INTERRUPT_REASON_SERVER_NO_RANGE;
368 default: // All other errors.
369 // Redirection and informational codes should have been handled earlier
371 DCHECK_NE(3, response_code / 100);
372 DCHECK_NE(1, response_code / 100);
373 reason = DOWNLOAD_INTERRUPT_REASON_SERVER_FAILED;
378 std::string accept_ranges;
379 bool has_strong_validators = false;
380 if (request()->response_headers()) {
381 request()->response_headers()->EnumerateHeader(
382 NULL, "Accept-Ranges", &accept_ranges);
383 has_strong_validators =
384 request()->response_headers()->HasStrongValidators();
386 RecordAcceptsRanges(accept_ranges, bytes_read_, has_strong_validators);
387 RecordNetworkBlockage(base::TimeTicks::Now() - download_start_time_,
390 CallStartedCB(NULL, reason);
392 // Send the info down the stream. Conditional is in case we get
393 // OnResponseCompleted without OnResponseStarted.
395 stream_writer_->Close(reason);
397 // If the error mapped to something unknown, record it so that
398 // we can drill down.
399 if (reason == DOWNLOAD_INTERRUPT_REASON_NETWORK_FAILED) {
400 UMA_HISTOGRAM_CUSTOM_ENUMERATION("Download.MapErrorNetworkFailed",
401 std::abs(status.error()),
402 net::GetAllErrorCodesForUma());
405 stream_writer_.reset(); // We no longer need the stream.
409 void DownloadResourceHandler::OnDataDownloaded(
411 int bytes_downloaded) {
415 void DownloadResourceHandler::PauseRequest() {
416 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
421 void DownloadResourceHandler::ResumeRequest() {
422 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
423 DCHECK_LT(0, pause_count_);
429 if (pause_count_ > 0)
432 was_deferred_ = false;
433 if (!last_stream_pause_time_.is_null()) {
434 total_pause_time_ += (base::TimeTicks::Now() - last_stream_pause_time_);
435 last_stream_pause_time_ = base::TimeTicks();
438 controller()->Resume();
441 void DownloadResourceHandler::CancelRequest() {
442 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
444 const ResourceRequestInfo* info = GetRequestInfo();
445 ResourceDispatcherHostImpl::Get()->CancelRequest(
447 info->GetRequestID());
448 // This object has been deleted.
451 std::string DownloadResourceHandler::DebugString() const {
452 const ResourceRequestInfo* info = GetRequestInfo();
453 return base::StringPrintf("{"
457 " request_id = " "%d"
462 request()->url().spec().c_str() :
465 info->GetRequestID(),
469 DownloadResourceHandler::~DownloadResourceHandler() {
470 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
472 // This won't do anything if the callback was called before.
473 // If it goes through, it will likely be because OnWillStart() returned
474 // false somewhere in the chain of resource handlers.
475 CallStartedCB(NULL, DOWNLOAD_INTERRUPT_REASON_NETWORK_FAILED);
477 // Remove output stream callback if a stream exists.
479 stream_writer_->RegisterCallback(base::Closure());
481 UMA_HISTOGRAM_TIMES("SB2.DownloadDuration",
482 base::TimeTicks::Now() - download_start_time_);
485 } // namespace content