Upstream version 7.35.139.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/web_contents.h"
29 #include "content/public/common/resource_response.h"
30 #include "net/base/io_buffer.h"
31 #include "net/base/net_errors.h"
32 #include "net/http/http_response_headers.h"
33 #include "net/http/http_status_code.h"
34 #include "net/url_request/url_request_context.h"
35
36 namespace content {
37
38 struct DownloadResourceHandler::DownloadTabInfo {
39   GURL tab_url;
40   GURL tab_referrer_url;
41 };
42
43 namespace {
44
45 void CallStartedCBOnUIThread(
46     const DownloadUrlParameters::OnStartedCallback& started_cb,
47     DownloadItem* item,
48     DownloadInterruptReason interrupt_reason) {
49   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
50
51   if (started_cb.is_null())
52     return;
53   started_cb.Run(item, interrupt_reason);
54 }
55
56 // Static function in order to prevent any accidental accesses to
57 // DownloadResourceHandler members from the UI thread.
58 static void StartOnUIThread(
59     scoped_ptr<DownloadCreateInfo> info,
60     DownloadResourceHandler::DownloadTabInfo* tab_info,
61     scoped_ptr<ByteStreamReader> stream,
62     const DownloadUrlParameters::OnStartedCallback& started_cb) {
63   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
64
65   DownloadManager* download_manager = info->request_handle.GetDownloadManager();
66   if (!download_manager) {
67     // NULL in unittests or if the page closed right after starting the
68     // download.
69     if (!started_cb.is_null())
70       started_cb.Run(NULL, DOWNLOAD_INTERRUPT_REASON_USER_CANCELED);
71
72     // |stream| gets deleted on non-FILE thread, but it's ok since
73     // we're not using stream_writer_ yet.
74
75     return;
76   }
77
78   info->tab_url = tab_info->tab_url;
79   info->tab_referrer_url = tab_info->tab_referrer_url;
80
81   download_manager->StartDownload(info.Pass(), stream.Pass(), started_cb);
82 }
83
84 void InitializeDownloadTabInfoOnUIThread(
85     const DownloadRequestHandle& request_handle,
86     DownloadResourceHandler::DownloadTabInfo* tab_info) {
87   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
88
89   WebContents* web_contents = request_handle.GetWebContents();
90   if (web_contents) {
91     NavigationEntry* entry = web_contents->GetController().GetVisibleEntry();
92     if (entry) {
93       tab_info->tab_url = entry->GetURL();
94       tab_info->tab_referrer_url = entry->GetReferrer().url;
95     }
96   }
97 }
98
99 }  // namespace
100
101 const int DownloadResourceHandler::kDownloadByteStreamSize = 100 * 1024;
102
103 DownloadResourceHandler::DownloadResourceHandler(
104     uint32 id,
105     net::URLRequest* request,
106     const DownloadUrlParameters::OnStartedCallback& started_cb,
107     scoped_ptr<DownloadSaveInfo> save_info)
108     : ResourceHandler(request),
109       download_id_(id),
110       started_cb_(started_cb),
111       save_info_(save_info.Pass()),
112       last_buffer_size_(0),
113       bytes_read_(0),
114       pause_count_(0),
115       was_deferred_(false),
116       on_response_started_called_(false) {
117   RecordDownloadCount(UNTHROTTLED_COUNT);
118
119   // Do UI thread initialization asap after DownloadResourceHandler creation
120   // since the tab could be navigated before StartOnUIThread gets called.
121   const ResourceRequestInfoImpl* request_info = GetRequestInfo();
122   tab_info_ = new DownloadTabInfo();
123   BrowserThread::PostTask(
124       BrowserThread::UI,
125       FROM_HERE,
126       base::Bind(&InitializeDownloadTabInfoOnUIThread,
127                  DownloadRequestHandle(AsWeakPtr(),
128                                        request_info->GetChildID(),
129                                        request_info->GetRouteID(),
130                                        request_info->GetRequestID()),
131                  tab_info_));
132 }
133
134 bool DownloadResourceHandler::OnUploadProgress(int request_id,
135                                                uint64 position,
136                                                uint64 size) {
137   return true;
138 }
139
140 bool DownloadResourceHandler::OnRequestRedirected(
141     int request_id,
142     const GURL& url,
143     ResourceResponse* response,
144     bool* defer) {
145   // We treat a download as a main frame load, and thus update the policy URL
146   // on redirects.
147   request()->set_first_party_for_cookies(url);
148   return true;
149 }
150
151 // Send the download creation information to the download thread.
152 bool DownloadResourceHandler::OnResponseStarted(
153     int request_id,
154     ResourceResponse* response,
155     bool* defer) {
156   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
157   // There can be only one (call)
158   DCHECK(!on_response_started_called_);
159   on_response_started_called_ = true;
160
161   VLOG(20) << __FUNCTION__ << "()" << DebugString()
162            << " request_id = " << request_id;
163   download_start_time_ = base::TimeTicks::Now();
164
165   // If it's a download, we don't want to poison the cache with it.
166   request()->StopCaching();
167
168   // Lower priority as well, so downloads don't contend for resources
169   // with main frames.
170   request()->SetPriority(net::IDLE);
171
172   // If the content-length header is not present (or contains something other
173   // than numbers), the incoming content_length is -1 (unknown size).
174   // Set the content length to 0 to indicate unknown size to DownloadManager.
175   int64 content_length =
176       response->head.content_length > 0 ? response->head.content_length : 0;
177
178   const ResourceRequestInfoImpl* request_info = GetRequestInfo();
179
180   // Deleted in DownloadManager.
181   scoped_ptr<DownloadCreateInfo> info(
182       new DownloadCreateInfo(base::Time::Now(),
183                              content_length,
184                              request()->net_log(),
185                              request_info->HasUserGesture(),
186                              request_info->GetPageTransition(),
187                              save_info_.Pass()));
188
189   // Create the ByteStream for sending data to the download sink.
190   scoped_ptr<ByteStreamReader> stream_reader;
191   CreateByteStream(
192       base::MessageLoopProxy::current(),
193       BrowserThread::GetMessageLoopProxyForThread(BrowserThread::FILE),
194       kDownloadByteStreamSize, &stream_writer_, &stream_reader);
195   stream_writer_->RegisterCallback(
196       base::Bind(&DownloadResourceHandler::ResumeRequest, AsWeakPtr()));
197
198   info->download_id = download_id_;
199   info->url_chain = request()->url_chain();
200   info->referrer_url = GURL(request()->referrer());
201   info->mime_type = response->head.mime_type;
202   info->remote_address = request()->GetSocketAddress().host();
203   request()->GetResponseHeaderByName("content-disposition",
204                                      &info->content_disposition);
205   RecordDownloadMimeType(info->mime_type);
206   RecordDownloadContentDisposition(info->content_disposition);
207
208   info->request_handle =
209       DownloadRequestHandle(AsWeakPtr(), request_info->GetChildID(),
210                             request_info->GetRouteID(),
211                             request_info->GetRequestID());
212
213   // Get the last modified time and etag.
214   const net::HttpResponseHeaders* headers = request()->response_headers();
215   if (headers) {
216     if (headers->HasStrongValidators()) {
217       // If we don't have strong validators as per RFC 2616 section 13.3.3, then
218       // we neither store nor use them for range requests.
219       if (!headers->EnumerateHeader(NULL, "Last-Modified",
220                                     &info->last_modified))
221         info->last_modified.clear();
222       if (!headers->EnumerateHeader(NULL, "ETag", &info->etag))
223         info->etag.clear();
224     }
225
226     int status = headers->response_code();
227     if (2 == status / 100  && status != net::HTTP_PARTIAL_CONTENT) {
228       // Success & not range response; if we asked for a range, we didn't
229       // get it--reset the file pointers to reflect that.
230       info->save_info->offset = 0;
231       info->save_info->hash_state = "";
232     }
233
234     if (!headers->GetMimeType(&info->original_mime_type))
235       info->original_mime_type.clear();
236   }
237
238   // Blink verifies that the requester of this download is allowed to set a
239   // suggested name for the security origin of the downlaod URL. However, this
240   // assumption doesn't hold if there were cross origin redirects. Therefore,
241   // clear the suggested_name for such requests.
242   if (info->url_chain.size() > 1 &&
243       info->url_chain.front().GetOrigin() != info->url_chain.back().GetOrigin())
244     info->save_info->suggested_name.clear();
245
246   BrowserThread::PostTask(
247       BrowserThread::UI, FROM_HERE,
248       base::Bind(&StartOnUIThread,
249                  base::Passed(&info),
250                  base::Owned(tab_info_),
251                  base::Passed(&stream_reader),
252                  // Pass to StartOnUIThread so that variable
253                  // access is always on IO thread but function
254                  // is called on UI thread.
255                  started_cb_));
256   // Now owned by the task that was just posted.
257   tab_info_ = NULL;
258   // Guaranteed to be called in StartOnUIThread
259   started_cb_.Reset();
260
261   return true;
262 }
263
264 void DownloadResourceHandler::CallStartedCB(
265     DownloadItem* item,
266     DownloadInterruptReason interrupt_reason) {
267   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
268   if (started_cb_.is_null())
269     return;
270   BrowserThread::PostTask(
271       BrowserThread::UI,
272       FROM_HERE,
273       base::Bind(
274           &CallStartedCBOnUIThread, started_cb_, item, interrupt_reason));
275   started_cb_.Reset();
276 }
277
278 bool DownloadResourceHandler::OnWillStart(int request_id,
279                                           const GURL& url,
280                                           bool* defer) {
281   return true;
282 }
283
284 bool DownloadResourceHandler::OnBeforeNetworkStart(int request_id,
285                                                    const GURL& url,
286                                                    bool* defer) {
287   return true;
288 }
289
290 // Create a new buffer, which will be handed to the download thread for file
291 // writing and deletion.
292 bool DownloadResourceHandler::OnWillRead(int request_id,
293                                          scoped_refptr<net::IOBuffer>* buf,
294                                          int* buf_size,
295                                          int min_size) {
296   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
297   DCHECK(buf && buf_size);
298   DCHECK(!read_buffer_.get());
299
300   *buf_size = min_size < 0 ? kReadBufSize : min_size;
301   last_buffer_size_ = *buf_size;
302   read_buffer_ = new net::IOBuffer(*buf_size);
303   *buf = read_buffer_.get();
304   return true;
305 }
306
307 // Pass the buffer to the download file writer.
308 bool DownloadResourceHandler::OnReadCompleted(int request_id, int bytes_read,
309                                               bool* defer) {
310   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
311   DCHECK(read_buffer_.get());
312
313   base::TimeTicks now(base::TimeTicks::Now());
314   if (!last_read_time_.is_null()) {
315     double seconds_since_last_read = (now - last_read_time_).InSecondsF();
316     if (now == last_read_time_)
317       // Use 1/10 ms as a "very small number" so that we avoid
318       // divide-by-zero error and still record a very high potential bandwidth.
319       seconds_since_last_read = 0.00001;
320
321     double actual_bandwidth = (bytes_read)/seconds_since_last_read;
322     double potential_bandwidth = last_buffer_size_/seconds_since_last_read;
323     RecordBandwidth(actual_bandwidth, potential_bandwidth);
324   }
325   last_read_time_ = now;
326
327   if (!bytes_read)
328     return true;
329   bytes_read_ += bytes_read;
330   DCHECK(read_buffer_.get());
331
332   // Take the data ship it down the stream.  If the stream is full, pause the
333   // request; the stream callback will resume it.
334   if (!stream_writer_->Write(read_buffer_, bytes_read)) {
335     PauseRequest();
336     *defer = was_deferred_ = true;
337     last_stream_pause_time_ = now;
338   }
339
340   read_buffer_ = NULL;  // Drop our reference.
341
342   if (pause_count_ > 0)
343     *defer = was_deferred_ = true;
344
345   return true;
346 }
347
348 void DownloadResourceHandler::OnResponseCompleted(
349     int request_id,
350     const net::URLRequestStatus& status,
351     const std::string& security_info,
352     bool* defer) {
353   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
354   int response_code = status.is_success() ? request()->GetResponseCode() : 0;
355   VLOG(20) << __FUNCTION__ << "()" << DebugString()
356            << " request_id = " << request_id
357            << " status.status() = " << status.status()
358            << " status.error() = " << status.error()
359            << " response_code = " << response_code;
360
361   net::Error error_code = net::OK;
362   if (status.status() == net::URLRequestStatus::FAILED ||
363       // Note cancels as failures too.
364       status.status() == net::URLRequestStatus::CANCELED) {
365     error_code = static_cast<net::Error>(status.error());  // Normal case.
366     // Make sure that at least the fact of failure comes through.
367     if (error_code == net::OK)
368       error_code = net::ERR_FAILED;
369   }
370
371   // ERR_CONTENT_LENGTH_MISMATCH and ERR_INCOMPLETE_CHUNKED_ENCODING are
372   // allowed since a number of servers in the wild close the connection too
373   // early by mistake. Other browsers - IE9, Firefox 11.0, and Safari 5.1.4 -
374   // treat downloads as complete in both cases, so we follow their lead.
375   if (error_code == net::ERR_CONTENT_LENGTH_MISMATCH ||
376       error_code == net::ERR_INCOMPLETE_CHUNKED_ENCODING) {
377     error_code = net::OK;
378   }
379   DownloadInterruptReason reason =
380       ConvertNetErrorToInterruptReason(
381         error_code, DOWNLOAD_INTERRUPT_FROM_NETWORK);
382
383   if (status.status() == net::URLRequestStatus::CANCELED &&
384       status.error() == net::ERR_ABORTED) {
385     // CANCELED + ERR_ABORTED == something outside of the network
386     // stack cancelled the request.  There aren't that many things that
387     // could do this to a download request (whose lifetime is separated from
388     // the tab from which it came).  We map this to USER_CANCELLED as the
389     // case we know about (system suspend because of laptop close) corresponds
390     // to a user action.
391     // TODO(ahendrickson) -- Find a better set of codes to use here, as
392     // CANCELED/ERR_ABORTED can occur for reasons other than user cancel.
393     reason = DOWNLOAD_INTERRUPT_REASON_USER_CANCELED;
394   }
395
396   if (status.is_success() &&
397       reason == DOWNLOAD_INTERRUPT_REASON_NONE &&
398       request()->response_headers()) {
399     // Handle server's response codes.
400     switch(response_code) {
401       case -1:                          // Non-HTTP request.
402       case net::HTTP_OK:
403       case net::HTTP_CREATED:
404       case net::HTTP_ACCEPTED:
405       case net::HTTP_NON_AUTHORITATIVE_INFORMATION:
406       case net::HTTP_RESET_CONTENT:
407       case net::HTTP_PARTIAL_CONTENT:
408         // Expected successful codes.
409         break;
410       case net::HTTP_NO_CONTENT:
411       case net::HTTP_NOT_FOUND:
412         reason = DOWNLOAD_INTERRUPT_REASON_SERVER_BAD_CONTENT;
413         break;
414       case net::HTTP_PRECONDITION_FAILED:
415         // Failed our 'If-Unmodified-Since' or 'If-Match'; see
416         // download_manager_impl.cc BeginDownload()
417         reason = DOWNLOAD_INTERRUPT_REASON_SERVER_PRECONDITION;
418         break;
419       case net::HTTP_REQUESTED_RANGE_NOT_SATISFIABLE:
420         // Retry by downloading from the start automatically:
421         // If we haven't received data when we get this error, we won't.
422         reason = DOWNLOAD_INTERRUPT_REASON_SERVER_NO_RANGE;
423         break;
424       default:    // All other errors.
425         // Redirection and informational codes should have been handled earlier
426         // in the stack.
427         DCHECK_NE(3, response_code / 100);
428         DCHECK_NE(1, response_code / 100);
429         reason = DOWNLOAD_INTERRUPT_REASON_SERVER_FAILED;
430         break;
431     }
432   }
433
434   std::string accept_ranges;
435   bool has_strong_validators = false;
436   if (request()->response_headers()) {
437     request()->response_headers()->EnumerateHeader(
438         NULL, "Accept-Ranges", &accept_ranges);
439     has_strong_validators =
440         request()->response_headers()->HasStrongValidators();
441   }
442   RecordAcceptsRanges(accept_ranges, bytes_read_, has_strong_validators);
443   RecordNetworkBlockage(base::TimeTicks::Now() - download_start_time_,
444                         total_pause_time_);
445
446   CallStartedCB(NULL, reason);
447
448   // Send the info down the stream.  Conditional is in case we get
449   // OnResponseCompleted without OnResponseStarted.
450   if (stream_writer_)
451     stream_writer_->Close(reason);
452
453   // If the error mapped to something unknown, record it so that
454   // we can drill down.
455   if (reason == DOWNLOAD_INTERRUPT_REASON_NETWORK_FAILED) {
456     UMA_HISTOGRAM_CUSTOM_ENUMERATION("Download.MapErrorNetworkFailed",
457                                      std::abs(status.error()),
458                                      net::GetAllErrorCodesForUma());
459   }
460
461   stream_writer_.reset();  // We no longer need the stream.
462   read_buffer_ = NULL;
463 }
464
465 void DownloadResourceHandler::OnDataDownloaded(
466     int request_id,
467     int bytes_downloaded) {
468   NOTREACHED();
469 }
470
471 void DownloadResourceHandler::PauseRequest() {
472   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
473
474   ++pause_count_;
475 }
476
477 void DownloadResourceHandler::ResumeRequest() {
478   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
479   DCHECK_LT(0, pause_count_);
480
481   --pause_count_;
482
483   if (!was_deferred_)
484     return;
485   if (pause_count_ > 0)
486     return;
487
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();
492   }
493
494   controller()->Resume();
495 }
496
497 void DownloadResourceHandler::CancelRequest() {
498   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
499
500   const ResourceRequestInfo* info = GetRequestInfo();
501   ResourceDispatcherHostImpl::Get()->CancelRequest(
502       info->GetChildID(),
503       info->GetRequestID());
504   // This object has been deleted.
505 }
506
507 std::string DownloadResourceHandler::DebugString() const {
508   const ResourceRequestInfo* info = GetRequestInfo();
509   return base::StringPrintf("{"
510                             " url_ = " "\"%s\""
511                             " info = {"
512                             " child_id = " "%d"
513                             " request_id = " "%d"
514                             " route_id = " "%d"
515                             " }"
516                             " }",
517                             request() ?
518                                 request()->url().spec().c_str() :
519                                 "<NULL request>",
520                             info->GetChildID(),
521                             info->GetRequestID(),
522                             info->GetRouteID());
523 }
524
525 DownloadResourceHandler::~DownloadResourceHandler() {
526   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
527
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);
532
533   // Remove output stream callback if a stream exists.
534   if (stream_writer_)
535     stream_writer_->RegisterCallback(base::Closure());
536
537   // tab_info_ must be destroyed on UI thread, since
538   // InitializeDownloadTabInfoOnUIThread might still be using it.
539   if (tab_info_)
540     BrowserThread::DeleteSoon(BrowserThread::UI, FROM_HERE, tab_info_);
541
542   UMA_HISTOGRAM_TIMES("SB2.DownloadDuration",
543                       base::TimeTicks::Now() - download_start_time_);
544 }
545
546 }  // namespace content