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
,
41 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI
));
43 if (started_cb
.is_null())
45 started_cb
.Run(item
, error
);
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
, net::ERR_ACCESS_DENIED
);
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
)
78 render_view_id_(0), // Actually initialized below.
81 started_cb_(started_cb
),
82 save_info_(save_info
.Pass()),
87 on_response_started_called_(false) {
88 ResourceRequestInfoImpl
* info(ResourceRequestInfoImpl::ForRequest(request
));
89 global_id_
= info
->GetGlobalRequestID();
90 render_view_id_
= info
->GetRouteID();
92 RecordDownloadCount(UNTHROTTLED_COUNT
);
95 bool DownloadResourceHandler::OnUploadProgress(int request_id
,
101 bool DownloadResourceHandler::OnRequestRedirected(
104 ResourceResponse
* response
,
106 // We treat a download as a main frame load, and thus update the policy URL
108 request_
->set_first_party_for_cookies(url
);
112 // Send the download creation information to the download thread.
113 bool DownloadResourceHandler::OnResponseStarted(
115 ResourceResponse
* response
,
117 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO
));
118 // There can be only one (call)
119 DCHECK(!on_response_started_called_
);
120 on_response_started_called_
= true;
122 VLOG(20) << __FUNCTION__
<< "()" << DebugString()
123 << " request_id = " << request_id
;
124 download_start_time_
= base::TimeTicks::Now();
126 // If it's a download, we don't want to poison the cache with it.
127 request_
->StopCaching();
129 // Lower priority as well, so downloads don't contend for resources
131 request_
->SetPriority(net::IDLE
);
133 std::string content_disposition
;
134 request_
->GetResponseHeaderByName("content-disposition",
135 &content_disposition
);
136 SetContentDisposition(content_disposition
);
137 SetContentLength(response
->head
.content_length
);
139 const ResourceRequestInfoImpl
* request_info
=
140 ResourceRequestInfoImpl::ForRequest(request_
);
142 // Deleted in DownloadManager.
143 scoped_ptr
<DownloadCreateInfo
> info(new DownloadCreateInfo(
144 base::Time::Now(), content_length_
,
145 request_
->net_log(), request_info
->HasUserGesture(),
146 request_info
->GetPageTransition()));
148 // Create the ByteStream for sending data to the download sink.
149 scoped_ptr
<ByteStreamReader
> stream_reader
;
151 base::MessageLoopProxy::current(),
152 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::FILE),
153 kDownloadByteStreamSize
, &stream_writer_
, &stream_reader
);
154 stream_writer_
->RegisterCallback(
155 base::Bind(&DownloadResourceHandler::ResumeRequest
, AsWeakPtr()));
157 info
->download_id
= download_id_
;
158 info
->url_chain
= request_
->url_chain();
159 info
->referrer_url
= GURL(request_
->referrer());
160 info
->start_time
= base::Time::Now();
161 info
->total_bytes
= content_length_
;
162 info
->has_user_gesture
= request_info
->HasUserGesture();
163 info
->content_disposition
= content_disposition_
;
164 info
->mime_type
= response
->head
.mime_type
;
165 info
->remote_address
= request_
->GetSocketAddress().host();
166 RecordDownloadMimeType(info
->mime_type
);
167 RecordDownloadContentDisposition(info
->content_disposition
);
169 info
->request_handle
=
170 DownloadRequestHandle(AsWeakPtr(), global_id_
.child_id
,
171 render_view_id_
, global_id_
.request_id
);
173 // Get the last modified time and etag.
174 const net::HttpResponseHeaders
* headers
= request_
->response_headers();
176 std::string last_modified_hdr
;
177 if (headers
->EnumerateHeader(NULL
, "Last-Modified", &last_modified_hdr
))
178 info
->last_modified
= last_modified_hdr
;
179 if (headers
->EnumerateHeader(NULL
, "ETag", &etag_
))
182 int status
= headers
->response_code();
183 if (2 == status
/ 100 && status
!= net::HTTP_PARTIAL_CONTENT
) {
184 // Success & not range response; if we asked for a range, we didn't
185 // get it--reset the file pointers to reflect that.
186 save_info_
->offset
= 0;
187 save_info_
->hash_state
= "";
191 std::string content_type_header
;
192 if (!response
->head
.headers
.get() ||
193 !response
->head
.headers
->GetMimeType(&content_type_header
))
194 content_type_header
= "";
195 info
->original_mime_type
= content_type_header
;
197 if (!response
->head
.headers
.get() ||
198 !response
->head
.headers
->EnumerateHeader(
199 NULL
, "Accept-Ranges", &accept_ranges_
)) {
203 info
->save_info
= save_info_
.Pass();
205 BrowserThread::PostTask(
206 BrowserThread::UI
, FROM_HERE
,
207 base::Bind(&StartOnUIThread
,
209 base::Passed(&stream_reader
),
210 // Pass to StartOnUIThread so that variable
211 // access is always on IO thread but function
212 // is called on UI thread.
214 // Guaranteed to be called in StartOnUIThread
220 void DownloadResourceHandler::CallStartedCB(
221 DownloadItem
* item
, net::Error error
) {
222 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO
));
223 if (started_cb_
.is_null())
225 BrowserThread::PostTask(
226 BrowserThread::UI
, FROM_HERE
,
227 base::Bind(&CallStartedCBOnUIThread
, started_cb_
, item
, error
));
231 bool DownloadResourceHandler::OnWillStart(int request_id
,
237 // Create a new buffer, which will be handed to the download thread for file
238 // writing and deletion.
239 bool DownloadResourceHandler::OnWillRead(int request_id
, net::IOBuffer
** buf
,
240 int* buf_size
, int min_size
) {
241 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO
));
242 DCHECK(buf
&& buf_size
);
243 DCHECK(!read_buffer_
.get());
245 *buf_size
= min_size
< 0 ? kReadBufSize
: min_size
;
246 last_buffer_size_
= *buf_size
;
247 read_buffer_
= new net::IOBuffer(*buf_size
);
248 *buf
= read_buffer_
.get();
252 // Pass the buffer to the download file writer.
253 bool DownloadResourceHandler::OnReadCompleted(int request_id
, int bytes_read
,
255 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO
));
256 DCHECK(read_buffer_
.get());
258 base::TimeTicks
now(base::TimeTicks::Now());
259 if (!last_read_time_
.is_null()) {
260 double seconds_since_last_read
= (now
- last_read_time_
).InSecondsF();
261 if (now
== last_read_time_
)
262 // Use 1/10 ms as a "very small number" so that we avoid
263 // divide-by-zero error and still record a very high potential bandwidth.
264 seconds_since_last_read
= 0.00001;
266 double actual_bandwidth
= (bytes_read
)/seconds_since_last_read
;
267 double potential_bandwidth
= last_buffer_size_
/seconds_since_last_read
;
268 RecordBandwidth(actual_bandwidth
, potential_bandwidth
);
270 last_read_time_
= now
;
274 bytes_read_
+= bytes_read
;
275 DCHECK(read_buffer_
.get());
277 // Take the data ship it down the stream. If the stream is full, pause the
278 // request; the stream callback will resume it.
279 if (!stream_writer_
->Write(read_buffer_
, bytes_read
)) {
281 *defer
= was_deferred_
= true;
282 last_stream_pause_time_
= now
;
285 read_buffer_
= NULL
; // Drop our reference.
287 if (pause_count_
> 0)
288 *defer
= was_deferred_
= true;
293 bool DownloadResourceHandler::OnResponseCompleted(
295 const net::URLRequestStatus
& status
,
296 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 RecordAcceptsRanges(accept_ranges_
, bytes_read_
, etag_
);
379 RecordNetworkBlockage(
380 base::TimeTicks::Now() - download_start_time_
, total_pause_time_
);
382 CallStartedCB(NULL
, error_code
);
384 // Send the info down the stream. Conditional is in case we get
385 // OnResponseCompleted without OnResponseStarted.
387 stream_writer_
->Close(reason
);
389 // If the error mapped to something unknown, record it so that
390 // we can drill down.
391 if (reason
== DOWNLOAD_INTERRUPT_REASON_NETWORK_FAILED
) {
392 UMA_HISTOGRAM_CUSTOM_ENUMERATION("Download.MapErrorNetworkFailed",
393 std::abs(status
.error()),
394 net::GetAllErrorCodesForUma());
397 stream_writer_
.reset(); // We no longer need the stream.
403 void DownloadResourceHandler::OnDataDownloaded(
405 int bytes_downloaded
) {
409 // If the content-length header is not present (or contains something other
410 // than numbers), the incoming content_length is -1 (unknown size).
411 // Set the content length to 0 to indicate unknown size to DownloadManager.
412 void DownloadResourceHandler::SetContentLength(const int64
& content_length
) {
413 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO
));
415 if (content_length
> 0)
416 content_length_
= content_length
;
419 void DownloadResourceHandler::SetContentDisposition(
420 const std::string
& content_disposition
) {
421 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO
));
422 content_disposition_
= content_disposition
;
425 void DownloadResourceHandler::PauseRequest() {
426 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO
));
431 void DownloadResourceHandler::ResumeRequest() {
432 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO
));
433 DCHECK_LT(0, pause_count_
);
439 if (pause_count_
> 0)
442 was_deferred_
= false;
443 if (!last_stream_pause_time_
.is_null()) {
444 total_pause_time_
+= (base::TimeTicks::Now() - last_stream_pause_time_
);
445 last_stream_pause_time_
= base::TimeTicks();
448 controller()->Resume();
451 void DownloadResourceHandler::CancelRequest() {
452 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO
));
454 ResourceDispatcherHostImpl::Get()->CancelRequest(
456 global_id_
.request_id
,
460 std::string
DownloadResourceHandler::DebugString() const {
461 return base::StringPrintf("{"
465 " request_id = " "%d"
467 " render_view_id_ = " "%d"
470 request_
->url().spec().c_str() :
473 global_id_
.request_id
,
477 DownloadResourceHandler::~DownloadResourceHandler() {
478 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO
));
480 // This won't do anything if the callback was called before.
481 // If it goes through, it will likely be because OnWillStart() returned
482 // false somewhere in the chain of resource handlers.
483 CallStartedCB(NULL
, net::ERR_ACCESS_DENIED
);
485 // Remove output stream callback if a stream exists.
487 stream_writer_
->RegisterCallback(base::Closure());
489 UMA_HISTOGRAM_TIMES("SB2.DownloadDuration",
490 base::TimeTicks::Now() - download_start_time_
);
493 } // namespace content