Upstream version 5.34.92.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/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"
33
34 namespace content {
35 namespace {
36
37 void CallStartedCBOnUIThread(
38     const DownloadUrlParameters::OnStartedCallback& started_cb,
39     DownloadItem* item,
40     DownloadInterruptReason interrupt_reason) {
41   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
42
43   if (started_cb.is_null())
44     return;
45   started_cb.Run(item, interrupt_reason);
46 }
47
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));
55
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
59     // download.
60     if (!started_cb.is_null())
61       started_cb.Run(NULL, DOWNLOAD_INTERRUPT_REASON_USER_CANCELED);
62     return;
63   }
64
65   download_manager->StartDownload(info.Pass(), stream.Pass(), started_cb);
66 }
67
68 }  // namespace
69
70 const int DownloadResourceHandler::kDownloadByteStreamSize = 100 * 1024;
71
72 DownloadResourceHandler::DownloadResourceHandler(
73     uint32 id,
74     net::URLRequest* request,
75     const DownloadUrlParameters::OnStartedCallback& started_cb,
76     scoped_ptr<DownloadSaveInfo> save_info)
77     : ResourceHandler(request),
78       download_id_(id),
79       started_cb_(started_cb),
80       save_info_(save_info.Pass()),
81       last_buffer_size_(0),
82       bytes_read_(0),
83       pause_count_(0),
84       was_deferred_(false),
85       on_response_started_called_(false) {
86   RecordDownloadCount(UNTHROTTLED_COUNT);
87 }
88
89 bool DownloadResourceHandler::OnUploadProgress(int request_id,
90                                                uint64 position,
91                                                uint64 size) {
92   return true;
93 }
94
95 bool DownloadResourceHandler::OnRequestRedirected(
96     int request_id,
97     const GURL& url,
98     ResourceResponse* response,
99     bool* defer) {
100   // We treat a download as a main frame load, and thus update the policy URL
101   // on redirects.
102   request()->set_first_party_for_cookies(url);
103   return true;
104 }
105
106 // Send the download creation information to the download thread.
107 bool DownloadResourceHandler::OnResponseStarted(
108     int request_id,
109     ResourceResponse* response,
110     bool* defer) {
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;
115
116   VLOG(20) << __FUNCTION__ << "()" << DebugString()
117            << " request_id = " << request_id;
118   download_start_time_ = base::TimeTicks::Now();
119
120   // If it's a download, we don't want to poison the cache with it.
121   request()->StopCaching();
122
123   // Lower priority as well, so downloads don't contend for resources
124   // with main frames.
125   request()->SetPriority(net::IDLE);
126
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;
132
133   const ResourceRequestInfoImpl* request_info = GetRequestInfo();
134
135   // Deleted in DownloadManager.
136   scoped_ptr<DownloadCreateInfo> info(
137       new DownloadCreateInfo(base::Time::Now(),
138                              content_length,
139                              request()->net_log(),
140                              request_info->HasUserGesture(),
141                              request_info->GetPageTransition(),
142                              save_info_.Pass()));
143
144   // Create the ByteStream for sending data to the download sink.
145   scoped_ptr<ByteStreamReader> stream_reader;
146   CreateByteStream(
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()));
152
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);
162
163   info->request_handle =
164       DownloadRequestHandle(AsWeakPtr(), request_info->GetChildID(),
165                             request_info->GetRouteID(),
166                             request_info->GetRequestID());
167
168   // Get the last modified time and etag.
169   const net::HttpResponseHeaders* headers = request()->response_headers();
170   if (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))
178         info->etag.clear();
179     }
180
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 = "";
187     }
188
189     if (!headers->GetMimeType(&info->original_mime_type))
190       info->original_mime_type.clear();
191   }
192
193   BrowserThread::PostTask(
194       BrowserThread::UI, FROM_HERE,
195       base::Bind(&StartOnUIThread,
196                  base::Passed(&info),
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.
201                  started_cb_));
202   // Guaranteed to be called in StartOnUIThread
203   started_cb_.Reset();
204
205   return true;
206 }
207
208 void DownloadResourceHandler::CallStartedCB(
209     DownloadItem* item,
210     DownloadInterruptReason interrupt_reason) {
211   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
212   if (started_cb_.is_null())
213     return;
214   BrowserThread::PostTask(
215       BrowserThread::UI,
216       FROM_HERE,
217       base::Bind(
218           &CallStartedCBOnUIThread, started_cb_, item, interrupt_reason));
219   started_cb_.Reset();
220 }
221
222 bool DownloadResourceHandler::OnWillStart(int request_id,
223                                           const GURL& url,
224                                           bool* defer) {
225   return true;
226 }
227
228 bool DownloadResourceHandler::OnBeforeNetworkStart(int request_id,
229                                                    const GURL& url,
230                                                    bool* defer) {
231   return true;
232 }
233
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,
238                                          int* buf_size,
239                                          int min_size) {
240   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
241   DCHECK(buf && buf_size);
242   DCHECK(!read_buffer_.get());
243
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();
248   return true;
249 }
250
251 // Pass the buffer to the download file writer.
252 bool DownloadResourceHandler::OnReadCompleted(int request_id, int bytes_read,
253                                               bool* defer) {
254   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
255   DCHECK(read_buffer_.get());
256
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;
264
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);
268   }
269   last_read_time_ = now;
270
271   if (!bytes_read)
272     return true;
273   bytes_read_ += bytes_read;
274   DCHECK(read_buffer_.get());
275
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)) {
279     PauseRequest();
280     *defer = was_deferred_ = true;
281     last_stream_pause_time_ = now;
282   }
283
284   read_buffer_ = NULL;  // Drop our reference.
285
286   if (pause_count_ > 0)
287     *defer = was_deferred_ = true;
288
289   return true;
290 }
291
292 void DownloadResourceHandler::OnResponseCompleted(
293     int request_id,
294     const net::URLRequestStatus& status,
295     const std::string& security_info,
296     bool* defer) {
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;
304
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;
313   }
314
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;
322   }
323   DownloadInterruptReason reason =
324       ConvertNetErrorToInterruptReason(
325         error_code, DOWNLOAD_INTERRUPT_FROM_NETWORK);
326
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
334     // to a user action.
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;
338   }
339
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.
346       case net::HTTP_OK:
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.
353         break;
354       case net::HTTP_NO_CONTENT:
355       case net::HTTP_NOT_FOUND:
356         reason = DOWNLOAD_INTERRUPT_REASON_SERVER_BAD_CONTENT;
357         break;
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;
362         break;
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;
367         break;
368       default:    // All other errors.
369         // Redirection and informational codes should have been handled earlier
370         // in the stack.
371         DCHECK_NE(3, response_code / 100);
372         DCHECK_NE(1, response_code / 100);
373         reason = DOWNLOAD_INTERRUPT_REASON_SERVER_FAILED;
374         break;
375     }
376   }
377
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();
385   }
386   RecordAcceptsRanges(accept_ranges, bytes_read_, has_strong_validators);
387   RecordNetworkBlockage(base::TimeTicks::Now() - download_start_time_,
388                         total_pause_time_);
389
390   CallStartedCB(NULL, reason);
391
392   // Send the info down the stream.  Conditional is in case we get
393   // OnResponseCompleted without OnResponseStarted.
394   if (stream_writer_)
395     stream_writer_->Close(reason);
396
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());
403   }
404
405   stream_writer_.reset();  // We no longer need the stream.
406   read_buffer_ = NULL;
407 }
408
409 void DownloadResourceHandler::OnDataDownloaded(
410     int request_id,
411     int bytes_downloaded) {
412   NOTREACHED();
413 }
414
415 void DownloadResourceHandler::PauseRequest() {
416   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
417
418   ++pause_count_;
419 }
420
421 void DownloadResourceHandler::ResumeRequest() {
422   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
423   DCHECK_LT(0, pause_count_);
424
425   --pause_count_;
426
427   if (!was_deferred_)
428     return;
429   if (pause_count_ > 0)
430     return;
431
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();
436   }
437
438   controller()->Resume();
439 }
440
441 void DownloadResourceHandler::CancelRequest() {
442   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
443
444   const ResourceRequestInfo* info = GetRequestInfo();
445   ResourceDispatcherHostImpl::Get()->CancelRequest(
446       info->GetChildID(),
447       info->GetRequestID());
448   // This object has been deleted.
449 }
450
451 std::string DownloadResourceHandler::DebugString() const {
452   const ResourceRequestInfo* info = GetRequestInfo();
453   return base::StringPrintf("{"
454                             " url_ = " "\"%s\""
455                             " info = {"
456                             " child_id = " "%d"
457                             " request_id = " "%d"
458                             " route_id = " "%d"
459                             " }"
460                             " }",
461                             request() ?
462                                 request()->url().spec().c_str() :
463                                 "<NULL request>",
464                             info->GetChildID(),
465                             info->GetRequestID(),
466                             info->GetRouteID());
467 }
468
469 DownloadResourceHandler::~DownloadResourceHandler() {
470   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
471
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);
476
477   // Remove output stream callback if a stream exists.
478   if (stream_writer_)
479     stream_writer_->RegisterCallback(base::Closure());
480
481   UMA_HISTOGRAM_TIMES("SB2.DownloadDuration",
482                       base::TimeTicks::Now() - download_start_time_);
483 }
484
485 }  // namespace content