Upstream version 7.36.149.0
[platform/framework/web/crosswalk.git] / src / content / browser / download / download_resource_handler.cc
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.
4
5 #include "content/browser/download/download_resource_handler.h"
6
7 #include <string>
8
9 #include "base/bind.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"
36
37 namespace content {
38
39 struct DownloadResourceHandler::DownloadTabInfo {
40   GURL tab_url;
41   GURL tab_referrer_url;
42 };
43
44 namespace {
45
46 void CallStartedCBOnUIThread(
47     const DownloadUrlParameters::OnStartedCallback& started_cb,
48     DownloadItem* item,
49     DownloadInterruptReason interrupt_reason) {
50   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
51
52   if (started_cb.is_null())
53     return;
54   started_cb.Run(item, interrupt_reason);
55 }
56
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));
65
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
69     // download.
70     if (!started_cb.is_null())
71       started_cb.Run(NULL, DOWNLOAD_INTERRUPT_REASON_USER_CANCELED);
72
73     // |stream| gets deleted on non-FILE thread, but it's ok since
74     // we're not using stream_writer_ yet.
75
76     return;
77   }
78
79   info->tab_url = tab_info->tab_url;
80   info->tab_referrer_url = tab_info->tab_referrer_url;
81
82   download_manager->StartDownload(info.Pass(), stream.Pass(), started_cb);
83 }
84
85 void InitializeDownloadTabInfoOnUIThread(
86     const DownloadRequestHandle& request_handle,
87     DownloadResourceHandler::DownloadTabInfo* tab_info) {
88   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
89
90   WebContents* web_contents = request_handle.GetWebContents();
91   if (web_contents) {
92     NavigationEntry* entry = web_contents->GetController().GetVisibleEntry();
93     if (entry) {
94       tab_info->tab_url = entry->GetURL();
95       tab_info->tab_referrer_url = entry->GetReferrer().url;
96     }
97   }
98 }
99
100 }  // namespace
101
102 const int DownloadResourceHandler::kDownloadByteStreamSize = 100 * 1024;
103
104 DownloadResourceHandler::DownloadResourceHandler(
105     uint32 id,
106     net::URLRequest* request,
107     const DownloadUrlParameters::OnStartedCallback& started_cb,
108     scoped_ptr<DownloadSaveInfo> save_info)
109     : ResourceHandler(request),
110       download_id_(id),
111       started_cb_(started_cb),
112       save_info_(save_info.Pass()),
113       last_buffer_size_(0),
114       bytes_read_(0),
115       pause_count_(0),
116       was_deferred_(false),
117       on_response_started_called_(false) {
118   RecordDownloadCount(UNTHROTTLED_COUNT);
119
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(
125       BrowserThread::UI,
126       FROM_HERE,
127       base::Bind(&InitializeDownloadTabInfoOnUIThread,
128                  DownloadRequestHandle(AsWeakPtr(),
129                                        request_info->GetChildID(),
130                                        request_info->GetRouteID(),
131                                        request_info->GetRequestID()),
132                  tab_info_));
133   power_save_blocker_ = PowerSaveBlocker::Create(
134       PowerSaveBlocker::kPowerSaveBlockPreventAppSuspension,
135       "Download in progress");
136 }
137
138 bool DownloadResourceHandler::OnUploadProgress(int request_id,
139                                                uint64 position,
140                                                uint64 size) {
141   return true;
142 }
143
144 bool DownloadResourceHandler::OnRequestRedirected(
145     int request_id,
146     const GURL& url,
147     ResourceResponse* response,
148     bool* defer) {
149   // We treat a download as a main frame load, and thus update the policy URL
150   // on redirects.
151   request()->set_first_party_for_cookies(url);
152   return true;
153 }
154
155 // Send the download creation information to the download thread.
156 bool DownloadResourceHandler::OnResponseStarted(
157     int request_id,
158     ResourceResponse* response,
159     bool* defer) {
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;
164
165   VLOG(20) << __FUNCTION__ << "()" << DebugString()
166            << " request_id = " << request_id;
167   download_start_time_ = base::TimeTicks::Now();
168
169   // If it's a download, we don't want to poison the cache with it.
170   request()->StopCaching();
171
172   // Lower priority as well, so downloads don't contend for resources
173   // with main frames.
174   request()->SetPriority(net::IDLE);
175
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;
181
182   const ResourceRequestInfoImpl* request_info = GetRequestInfo();
183
184   // Deleted in DownloadManager.
185   scoped_ptr<DownloadCreateInfo> info(
186       new DownloadCreateInfo(base::Time::Now(),
187                              content_length,
188                              request()->net_log(),
189                              request_info->HasUserGesture(),
190                              request_info->GetPageTransition(),
191                              save_info_.Pass()));
192
193   // Create the ByteStream for sending data to the download sink.
194   scoped_ptr<ByteStreamReader> stream_reader;
195   CreateByteStream(
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()));
201
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);
211
212   info->request_handle =
213       DownloadRequestHandle(AsWeakPtr(), request_info->GetChildID(),
214                             request_info->GetRouteID(),
215                             request_info->GetRequestID());
216
217   // Get the last modified time and etag.
218   const net::HttpResponseHeaders* headers = request()->response_headers();
219   if (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))
227         info->etag.clear();
228     }
229
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 = "";
236     }
237
238     if (!headers->GetMimeType(&info->original_mime_type))
239       info->original_mime_type.clear();
240   }
241
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();
249
250   BrowserThread::PostTask(
251       BrowserThread::UI, FROM_HERE,
252       base::Bind(&StartOnUIThread,
253                  base::Passed(&info),
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.
259                  started_cb_));
260   // Now owned by the task that was just posted.
261   tab_info_ = NULL;
262   // Guaranteed to be called in StartOnUIThread
263   started_cb_.Reset();
264
265   return true;
266 }
267
268 void DownloadResourceHandler::CallStartedCB(
269     DownloadItem* item,
270     DownloadInterruptReason interrupt_reason) {
271   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
272   if (started_cb_.is_null())
273     return;
274   BrowserThread::PostTask(
275       BrowserThread::UI,
276       FROM_HERE,
277       base::Bind(
278           &CallStartedCBOnUIThread, started_cb_, item, interrupt_reason));
279   started_cb_.Reset();
280 }
281
282 bool DownloadResourceHandler::OnWillStart(int request_id,
283                                           const GURL& url,
284                                           bool* defer) {
285   return true;
286 }
287
288 bool DownloadResourceHandler::OnBeforeNetworkStart(int request_id,
289                                                    const GURL& url,
290                                                    bool* defer) {
291   return true;
292 }
293
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,
298                                          int* buf_size,
299                                          int min_size) {
300   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
301   DCHECK(buf && buf_size);
302   DCHECK(!read_buffer_.get());
303
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();
308   return true;
309 }
310
311 // Pass the buffer to the download file writer.
312 bool DownloadResourceHandler::OnReadCompleted(int request_id, int bytes_read,
313                                               bool* defer) {
314   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
315   DCHECK(read_buffer_.get());
316
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;
324
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);
328   }
329   last_read_time_ = now;
330
331   if (!bytes_read)
332     return true;
333   bytes_read_ += bytes_read;
334   DCHECK(read_buffer_.get());
335
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)) {
339     PauseRequest();
340     *defer = was_deferred_ = true;
341     last_stream_pause_time_ = now;
342   }
343
344   read_buffer_ = NULL;  // Drop our reference.
345
346   if (pause_count_ > 0)
347     *defer = was_deferred_ = true;
348
349   return true;
350 }
351
352 void DownloadResourceHandler::OnResponseCompleted(
353     int request_id,
354     const net::URLRequestStatus& status,
355     const std::string& security_info,
356     bool* defer) {
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;
364
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;
373   }
374
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;
382   }
383   DownloadInterruptReason reason =
384       ConvertNetErrorToInterruptReason(
385         error_code, DOWNLOAD_INTERRUPT_FROM_NETWORK);
386
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
394     // to a user action.
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;
398   }
399
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.
406       case net::HTTP_OK:
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.
413         break;
414       case net::HTTP_NO_CONTENT:
415       case net::HTTP_NOT_FOUND:
416         reason = DOWNLOAD_INTERRUPT_REASON_SERVER_BAD_CONTENT;
417         break;
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;
422         break;
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;
427         break;
428       default:    // All other errors.
429         // Redirection and informational codes should have been handled earlier
430         // in the stack.
431         DCHECK_NE(3, response_code / 100);
432         DCHECK_NE(1, response_code / 100);
433         reason = DOWNLOAD_INTERRUPT_REASON_SERVER_FAILED;
434         break;
435     }
436   }
437
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();
445   }
446   RecordAcceptsRanges(accept_ranges, bytes_read_, has_strong_validators);
447   RecordNetworkBlockage(base::TimeTicks::Now() - download_start_time_,
448                         total_pause_time_);
449
450   CallStartedCB(NULL, reason);
451
452   // Send the info down the stream.  Conditional is in case we get
453   // OnResponseCompleted without OnResponseStarted.
454   if (stream_writer_)
455     stream_writer_->Close(reason);
456
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());
463   }
464
465   stream_writer_.reset();  // We no longer need the stream.
466   read_buffer_ = NULL;
467 }
468
469 void DownloadResourceHandler::OnDataDownloaded(
470     int request_id,
471     int bytes_downloaded) {
472   NOTREACHED();
473 }
474
475 void DownloadResourceHandler::PauseRequest() {
476   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
477
478   ++pause_count_;
479 }
480
481 void DownloadResourceHandler::ResumeRequest() {
482   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
483   DCHECK_LT(0, pause_count_);
484
485   --pause_count_;
486
487   if (!was_deferred_)
488     return;
489   if (pause_count_ > 0)
490     return;
491
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();
496   }
497
498   controller()->Resume();
499 }
500
501 void DownloadResourceHandler::CancelRequest() {
502   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
503
504   const ResourceRequestInfo* info = GetRequestInfo();
505   ResourceDispatcherHostImpl::Get()->CancelRequest(
506       info->GetChildID(),
507       info->GetRequestID());
508   // This object has been deleted.
509 }
510
511 std::string DownloadResourceHandler::DebugString() const {
512   const ResourceRequestInfo* info = GetRequestInfo();
513   return base::StringPrintf("{"
514                             " url_ = " "\"%s\""
515                             " info = {"
516                             " child_id = " "%d"
517                             " request_id = " "%d"
518                             " route_id = " "%d"
519                             " }"
520                             " }",
521                             request() ?
522                                 request()->url().spec().c_str() :
523                                 "<NULL request>",
524                             info->GetChildID(),
525                             info->GetRequestID(),
526                             info->GetRouteID());
527 }
528
529 DownloadResourceHandler::~DownloadResourceHandler() {
530   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
531
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);
536
537   // Remove output stream callback if a stream exists.
538   if (stream_writer_)
539     stream_writer_->RegisterCallback(base::Closure());
540
541   // tab_info_ must be destroyed on UI thread, since
542   // InitializeDownloadTabInfoOnUIThread might still be using it.
543   if (tab_info_)
544     BrowserThread::DeleteSoon(BrowserThread::UI, FROM_HERE, tab_info_);
545
546   UMA_HISTOGRAM_TIMES("SB2.DownloadDuration",
547                       base::TimeTicks::Now() - download_start_time_);
548 }
549
550 }  // namespace content