Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(38)

Side by Side Diff: content/browser/download/download_resource_handler.cc

Issue 1533583002: [Downloads] Factor out request handling logic between DRH and UD. (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@master
Patch Set: Address comments and change .Pass() -> std::move(...) per PRESUBMIT check Created 5 years ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved. 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 2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file. 3 // found in the LICENSE file.
4 4
5 #include "content/browser/download/download_resource_handler.h" 5 #include "content/browser/download/download_resource_handler.h"
6 6
7 #include <string> 7 #include <string>
8 8
9 #include "base/bind.h" 9 #include "base/bind.h"
10 #include "base/callback_helpers.h"
10 #include "base/location.h" 11 #include "base/location.h"
11 #include "base/logging.h" 12 #include "base/logging.h"
12 #include "base/metrics/histogram_macros.h"
13 #include "base/metrics/sparse_histogram.h"
14 #include "base/single_thread_task_runner.h"
15 #include "base/strings/stringprintf.h" 13 #include "base/strings/stringprintf.h"
16 #include "base/thread_task_runner_handle.h"
17 #include "content/browser/byte_stream.h" 14 #include "content/browser/byte_stream.h"
18 #include "content/browser/download/download_create_info.h" 15 #include "content/browser/download/download_create_info.h"
19 #include "content/browser/download/download_interrupt_reasons_impl.h" 16 #include "content/browser/download/download_interrupt_reasons_impl.h"
20 #include "content/browser/download/download_manager_impl.h" 17 #include "content/browser/download/download_manager_impl.h"
21 #include "content/browser/download/download_request_handle.h" 18 #include "content/browser/download/download_request_handle.h"
22 #include "content/browser/download/download_stats.h"
23 #include "content/browser/loader/resource_dispatcher_host_impl.h" 19 #include "content/browser/loader/resource_dispatcher_host_impl.h"
24 #include "content/browser/loader/resource_request_info_impl.h" 20 #include "content/browser/loader/resource_request_info_impl.h"
25 #include "content/public/browser/browser_thread.h" 21 #include "content/public/browser/browser_thread.h"
26 #include "content/public/browser/download_interrupt_reasons.h" 22 #include "content/public/browser/download_interrupt_reasons.h"
27 #include "content/public/browser/download_item.h"
28 #include "content/public/browser/download_manager_delegate.h"
29 #include "content/public/browser/navigation_entry.h" 23 #include "content/public/browser/navigation_entry.h"
30 #include "content/public/browser/power_save_blocker.h"
31 #include "content/public/browser/web_contents.h" 24 #include "content/public/browser/web_contents.h"
32 #include "content/public/common/resource_response.h" 25 #include "content/public/common/resource_response.h"
33 #include "net/base/io_buffer.h"
34 #include "net/base/net_errors.h"
35 #include "net/http/http_response_headers.h"
36 #include "net/http/http_status_code.h"
37 #include "net/url_request/url_request_context.h"
38 26
39 namespace content { 27 namespace content {
40 28
41 struct DownloadResourceHandler::DownloadTabInfo { 29 struct DownloadResourceHandler::DownloadTabInfo {
42 GURL tab_url; 30 GURL tab_url;
43 GURL tab_referrer_url; 31 GURL tab_referrer_url;
44 }; 32 };
45 33
46 namespace { 34 namespace {
47 35
48 void CallStartedCBOnUIThread(
49 const DownloadUrlParameters::OnStartedCallback& started_cb,
50 DownloadItem* item,
51 DownloadInterruptReason interrupt_reason) {
52 DCHECK_CURRENTLY_ON(BrowserThread::UI);
53
54 if (started_cb.is_null())
55 return;
56 started_cb.Run(item, interrupt_reason);
57 }
58
59 // Static function in order to prevent any accidental accesses to 36 // Static function in order to prevent any accidental accesses to
60 // DownloadResourceHandler members from the UI thread. 37 // DownloadResourceHandler members from the UI thread.
61 static void StartOnUIThread( 38 static void StartOnUIThread(
62 scoped_ptr<DownloadCreateInfo> info, 39 scoped_ptr<DownloadCreateInfo> info,
63 scoped_ptr<DownloadResourceHandler::DownloadTabInfo> tab_info, 40 scoped_ptr<DownloadResourceHandler::DownloadTabInfo> tab_info,
64 scoped_ptr<ByteStreamReader> stream, 41 scoped_ptr<ByteStreamReader> stream,
65 const DownloadUrlParameters::OnStartedCallback& started_cb) { 42 const DownloadUrlParameters::OnStartedCallback& started_cb) {
66 DCHECK_CURRENTLY_ON(BrowserThread::UI); 43 DCHECK_CURRENTLY_ON(BrowserThread::UI);
67 44
68 DownloadManager* download_manager = info->request_handle.GetDownloadManager(); 45 DownloadManager* download_manager =
46 info->request_handle->GetDownloadManager();
69 if (!download_manager) { 47 if (!download_manager) {
70 // NULL in unittests or if the page closed right after starting the 48 // NULL in unittests or if the page closed right after starting the
71 // download. 49 // download.
72 if (!started_cb.is_null()) 50 if (!started_cb.is_null())
73 started_cb.Run(NULL, DOWNLOAD_INTERRUPT_REASON_USER_CANCELED); 51 started_cb.Run(NULL, DOWNLOAD_INTERRUPT_REASON_USER_CANCELED);
74 52
75 // |stream| gets deleted on non-FILE thread, but it's ok since 53 // |stream| gets deleted on non-FILE thread, but it's ok since
76 // we're not using stream_writer_ yet. 54 // we're not using stream_writer_ yet.
77 55
78 return; 56 return;
79 } 57 }
80 58
81 info->tab_url = tab_info->tab_url; 59 info->tab_url = tab_info->tab_url;
82 info->tab_referrer_url = tab_info->tab_referrer_url; 60 info->tab_referrer_url = tab_info->tab_referrer_url;
83 61
84 download_manager->StartDownload(info.Pass(), stream.Pass(), started_cb); 62 download_manager->StartDownload(std::move(info), std::move(stream),
63 started_cb);
85 } 64 }
86 65
87 void InitializeDownloadTabInfoOnUIThread( 66 void InitializeDownloadTabInfoOnUIThread(
88 const DownloadRequestHandle& request_handle, 67 const DownloadRequestHandle& request_handle,
89 DownloadResourceHandler::DownloadTabInfo* tab_info) { 68 DownloadResourceHandler::DownloadTabInfo* tab_info) {
90 DCHECK_CURRENTLY_ON(BrowserThread::UI); 69 DCHECK_CURRENTLY_ON(BrowserThread::UI);
91 70
92 WebContents* web_contents = request_handle.GetWebContents(); 71 WebContents* web_contents = request_handle.GetWebContents();
93 if (web_contents) { 72 if (web_contents) {
94 NavigationEntry* entry = web_contents->GetController().GetVisibleEntry(); 73 NavigationEntry* entry = web_contents->GetController().GetVisibleEntry();
95 if (entry) { 74 if (entry) {
96 tab_info->tab_url = entry->GetURL(); 75 tab_info->tab_url = entry->GetURL();
97 tab_info->tab_referrer_url = entry->GetReferrer().url; 76 tab_info->tab_referrer_url = entry->GetReferrer().url;
98 } 77 }
99 } 78 }
100 } 79 }
101 80
102 void DeleteOnUIThread( 81 void DeleteOnUIThread(
103 scoped_ptr<DownloadResourceHandler::DownloadTabInfo> tab_info) {} 82 scoped_ptr<DownloadResourceHandler::DownloadTabInfo> tab_info) {}
104 83
105 } // namespace 84 } // namespace
106 85
107 const int DownloadResourceHandler::kDownloadByteStreamSize = 100 * 1024;
108
109 DownloadResourceHandler::DownloadResourceHandler( 86 DownloadResourceHandler::DownloadResourceHandler(
110 uint32 id, 87 uint32 id,
111 net::URLRequest* request, 88 net::URLRequest* request,
112 const DownloadUrlParameters::OnStartedCallback& started_cb, 89 const DownloadUrlParameters::OnStartedCallback& started_cb,
113 scoped_ptr<DownloadSaveInfo> save_info) 90 scoped_ptr<DownloadSaveInfo> save_info)
114 : ResourceHandler(request), 91 : ResourceHandler(request),
115 download_id_(id), 92 download_id_(id),
116 started_cb_(started_cb), 93 started_cb_(started_cb),
117 save_info_(save_info.Pass()),
118 tab_info_(new DownloadTabInfo()), 94 tab_info_(new DownloadTabInfo()),
119 last_buffer_size_(0), 95 core_(request,
120 bytes_read_(0), 96 std::move(save_info),
121 pause_count_(0), 97 base::Bind(&DownloadResourceHandler::OnCoreReadyToRead,
122 was_deferred_(false), 98 base::Unretained(this))) {
123 on_response_started_called_(false) {
124 RecordDownloadCount(UNTHROTTLED_COUNT);
125
126 // Do UI thread initialization for tab_info_ asap after 99 // Do UI thread initialization for tab_info_ asap after
127 // DownloadResourceHandler creation since the tab could be navigated 100 // DownloadResourceHandler creation since the tab could be navigated
128 // before StartOnUIThread gets called. This is safe because deletion 101 // before StartOnUIThread gets called. This is safe because deletion
129 // will occur via PostTask() as well, which will serialized behind this 102 // will occur via PostTask() as well, which will serialized behind this
130 // PostTask() 103 // PostTask()
131 const ResourceRequestInfoImpl* request_info = GetRequestInfo(); 104 const ResourceRequestInfoImpl* request_info = GetRequestInfo();
132 BrowserThread::PostTask( 105 BrowserThread::PostTask(
133 BrowserThread::UI, FROM_HERE, 106 BrowserThread::UI, FROM_HERE,
134 base::Bind(&InitializeDownloadTabInfoOnUIThread, 107 base::Bind(&InitializeDownloadTabInfoOnUIThread,
135 DownloadRequestHandle(AsWeakPtr(), request_info->GetChildID(), 108 DownloadRequestHandle(AsWeakPtr(), request_info->GetChildID(),
136 request_info->GetRouteID(), 109 request_info->GetRouteID(),
137 request_info->GetRequestID(), 110 request_info->GetRequestID(),
138 request_info->frame_tree_node_id()), 111 request_info->frame_tree_node_id()),
139 tab_info_.get())); 112 tab_info_.get()));
140 power_save_blocker_ = PowerSaveBlocker::Create( 113 }
141 PowerSaveBlocker::kPowerSaveBlockPreventAppSuspension, 114
142 PowerSaveBlocker::kReasonOther, "Download in progress"); 115 DownloadResourceHandler::~DownloadResourceHandler() {
116 // This won't do anything if the callback was called before.
117 // If it goes through, it will likely be because OnWillStart() returned
118 // false somewhere in the chain of resource handlers.
119 CallStartedCB(DOWNLOAD_INTERRUPT_REASON_NETWORK_FAILED);
120
121 if (tab_info_) {
122 BrowserThread::PostTask(
123 BrowserThread::UI, FROM_HERE,
124 base::Bind(&DeleteOnUIThread, base::Passed(&tab_info_)));
125 }
143 } 126 }
144 127
145 bool DownloadResourceHandler::OnRequestRedirected( 128 bool DownloadResourceHandler::OnRequestRedirected(
146 const net::RedirectInfo& redirect_info, 129 const net::RedirectInfo& redirect_info,
147 ResourceResponse* response, 130 ResourceResponse* response,
148 bool* defer) { 131 bool* defer) {
149 return true; 132 return true;
150 } 133 }
151 134
152 // Send the download creation information to the download thread. 135 // Send the download creation information to the download thread.
153 bool DownloadResourceHandler::OnResponseStarted( 136 bool DownloadResourceHandler::OnResponseStarted(
154 ResourceResponse* response, 137 ResourceResponse* response,
155 bool* defer) { 138 bool* defer) {
156 DCHECK_CURRENTLY_ON(BrowserThread::IO); 139 scoped_ptr<DownloadCreateInfo> create_info;
157 // There can be only one (call) 140 scoped_ptr<ByteStreamReader> stream_reader;
158 DCHECK(!on_response_started_called_);
159 on_response_started_called_ = true;
160 141
161 DVLOG(20) << __FUNCTION__ << "()" << DebugString(); 142 core_.OnResponseStarted(&create_info, &stream_reader);
162 download_start_time_ = base::TimeTicks::Now();
163
164 // If it's a download, we don't want to poison the cache with it.
165 request()->StopCaching();
166
167 // Lower priority as well, so downloads don't contend for resources
168 // with main frames.
169 request()->SetPriority(net::IDLE);
170
171 // If the content-length header is not present (or contains something other
172 // than numbers), the incoming content_length is -1 (unknown size).
173 // Set the content length to 0 to indicate unknown size to DownloadManager.
174 int64 content_length =
175 response->head.content_length > 0 ? response->head.content_length : 0;
176 143
177 const ResourceRequestInfoImpl* request_info = GetRequestInfo(); 144 const ResourceRequestInfoImpl* request_info = GetRequestInfo();
145 create_info->download_id = download_id_;
146 create_info->has_user_gesture = request_info->HasUserGesture();
147 create_info->transition_type = request_info->GetPageTransition();
148 create_info->request_handle.reset(new DownloadRequestHandle(
149 AsWeakPtr(), request_info->GetChildID(), request_info->GetRouteID(),
150 request_info->GetRequestID(), request_info->frame_tree_node_id()));
178 151
179 // Deleted in DownloadManager. 152 // The MIME type in ResourceResponse is the product of
180 scoped_ptr<DownloadCreateInfo> info( 153 // MimeTypeResourceHandler.
181 new DownloadCreateInfo(base::Time::Now(), 154 create_info->mime_type = response->head.mime_type;
182 content_length,
183 request()->net_log(),
184 request_info->HasUserGesture(),
185 request_info->GetPageTransition(),
186 save_info_.Pass()));
187
188 // Create the ByteStream for sending data to the download sink.
189 scoped_ptr<ByteStreamReader> stream_reader;
190 CreateByteStream(
191 base::ThreadTaskRunnerHandle::Get(),
192 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::FILE),
193 kDownloadByteStreamSize, &stream_writer_, &stream_reader);
194 stream_writer_->RegisterCallback(
195 base::Bind(&DownloadResourceHandler::ResumeRequest, AsWeakPtr()));
196
197 info->download_id = download_id_;
198 info->url_chain = request()->url_chain();
199 info->referrer_url = GURL(request()->referrer());
200 info->mime_type = response->head.mime_type;
201 info->remote_address = request()->GetSocketAddress().host();
202 if (request()->response_headers()) {
203 // Grab the first content-disposition header. There may be more than one,
204 // though as of this writing, the network stack ensures if there are, they
205 // are all duplicates.
206 request()->response_headers()->EnumerateHeader(
207 nullptr, "content-disposition", &info->content_disposition);
208 }
209 RecordDownloadMimeType(info->mime_type);
210 RecordDownloadContentDisposition(info->content_disposition);
211
212 info->request_handle = DownloadRequestHandle(
213 AsWeakPtr(), request_info->GetChildID(), request_info->GetRouteID(),
214 request_info->GetRequestID(), request_info->frame_tree_node_id());
215
216 // Get the last modified time and etag.
217 const net::HttpResponseHeaders* headers = request()->response_headers();
218 if (headers) {
219 if (headers->HasStrongValidators()) {
220 // If we don't have strong validators as per RFC 2616 section 13.3.3, then
221 // we neither store nor use them for range requests.
222 if (!headers->EnumerateHeader(NULL, "Last-Modified",
223 &info->last_modified))
224 info->last_modified.clear();
225 if (!headers->EnumerateHeader(NULL, "ETag", &info->etag))
226 info->etag.clear();
227 }
228
229 int status = headers->response_code();
230 if (2 == status / 100 && status != net::HTTP_PARTIAL_CONTENT) {
231 // Success & not range response; if we asked for a range, we didn't
232 // get it--reset the file pointers to reflect that.
233 info->save_info->offset = 0;
234 info->save_info->hash_state = "";
235 }
236
237 if (!headers->GetMimeType(&info->original_mime_type))
238 info->original_mime_type.clear();
239 }
240
241 // Blink verifies that the requester of this download is allowed to set a
242 // suggested name for the security origin of the downlaod URL. However, this
243 // assumption doesn't hold if there were cross origin redirects. Therefore,
244 // clear the suggested_name for such requests.
245 if (info->url_chain.size() > 1 &&
246 info->url_chain.front().GetOrigin() != info->url_chain.back().GetOrigin())
247 info->save_info->suggested_name.clear();
248 155
249 BrowserThread::PostTask( 156 BrowserThread::PostTask(
250 BrowserThread::UI, FROM_HERE, 157 BrowserThread::UI, FROM_HERE,
251 base::Bind(&StartOnUIThread, 158 base::Bind(&StartOnUIThread, base::Passed(&create_info),
252 base::Passed(&info), 159 base::Passed(&tab_info_), base::Passed(&stream_reader),
253 base::Passed(&tab_info_), 160 base::ResetAndReturn(&started_cb_)));
254 base::Passed(&stream_reader),
255 // Pass to StartOnUIThread so that variable
256 // access is always on IO thread but function
257 // is called on UI thread.
258 started_cb_));
259 // Guaranteed to be called in StartOnUIThread
260 started_cb_.Reset();
261
262 return true; 161 return true;
263 } 162 }
264 163
265 void DownloadResourceHandler::CallStartedCB( 164 void DownloadResourceHandler::CallStartedCB(
266 DownloadItem* item,
267 DownloadInterruptReason interrupt_reason) { 165 DownloadInterruptReason interrupt_reason) {
268 DCHECK_CURRENTLY_ON(BrowserThread::IO); 166 DCHECK_CURRENTLY_ON(BrowserThread::IO);
269 if (started_cb_.is_null()) 167 if (started_cb_.is_null())
270 return; 168 return;
271 BrowserThread::PostTask( 169 BrowserThread::PostTask(BrowserThread::UI, FROM_HERE,
272 BrowserThread::UI, 170 base::Bind(base::ResetAndReturn(&started_cb_),
273 FROM_HERE, 171 nullptr, interrupt_reason));
274 base::Bind(
275 &CallStartedCBOnUIThread, started_cb_, item, interrupt_reason));
276 started_cb_.Reset();
277 } 172 }
278 173
279 bool DownloadResourceHandler::OnWillStart(const GURL& url, bool* defer) { 174 bool DownloadResourceHandler::OnWillStart(const GURL& url, bool* defer) {
280 return true; 175 return true;
281 } 176 }
282 177
283 bool DownloadResourceHandler::OnBeforeNetworkStart(const GURL& url, 178 bool DownloadResourceHandler::OnBeforeNetworkStart(const GURL& url,
284 bool* defer) { 179 bool* defer) {
285 return true; 180 return true;
286 } 181 }
287 182
288 // Create a new buffer, which will be handed to the download thread for file 183 // Create a new buffer, which will be handed to the download thread for file
289 // writing and deletion. 184 // writing and deletion.
290 bool DownloadResourceHandler::OnWillRead(scoped_refptr<net::IOBuffer>* buf, 185 bool DownloadResourceHandler::OnWillRead(scoped_refptr<net::IOBuffer>* buf,
291 int* buf_size, 186 int* buf_size,
292 int min_size) { 187 int min_size) {
293 DCHECK_CURRENTLY_ON(BrowserThread::IO); 188 return core_.OnWillRead(buf, buf_size, min_size);
294 DCHECK(buf && buf_size);
295 DCHECK(!read_buffer_.get());
296
297 *buf_size = min_size < 0 ? kReadBufSize : min_size;
298 last_buffer_size_ = *buf_size;
299 read_buffer_ = new net::IOBuffer(*buf_size);
300 *buf = read_buffer_.get();
301 return true;
302 } 189 }
303 190
304 // Pass the buffer to the download file writer. 191 // Pass the buffer to the download file writer.
305 bool DownloadResourceHandler::OnReadCompleted(int bytes_read, bool* defer) { 192 bool DownloadResourceHandler::OnReadCompleted(int bytes_read, bool* defer) {
306 DCHECK_CURRENTLY_ON(BrowserThread::IO); 193 return core_.OnReadCompleted(bytes_read, defer);
307 DCHECK(read_buffer_.get());
308
309 base::TimeTicks now(base::TimeTicks::Now());
310 if (!last_read_time_.is_null()) {
311 double seconds_since_last_read = (now - last_read_time_).InSecondsF();
312 if (now == last_read_time_)
313 // Use 1/10 ms as a "very small number" so that we avoid
314 // divide-by-zero error and still record a very high potential bandwidth.
315 seconds_since_last_read = 0.00001;
316
317 double actual_bandwidth = (bytes_read)/seconds_since_last_read;
318 double potential_bandwidth = last_buffer_size_/seconds_since_last_read;
319 RecordBandwidth(actual_bandwidth, potential_bandwidth);
320 }
321 last_read_time_ = now;
322
323 if (!bytes_read)
324 return true;
325 bytes_read_ += bytes_read;
326 DCHECK(read_buffer_.get());
327
328 // Take the data ship it down the stream. If the stream is full, pause the
329 // request; the stream callback will resume it.
330 if (!stream_writer_->Write(read_buffer_, bytes_read)) {
331 PauseRequest();
332 *defer = was_deferred_ = true;
333 last_stream_pause_time_ = now;
334 }
335
336 read_buffer_ = NULL; // Drop our reference.
337
338 if (pause_count_ > 0)
339 *defer = was_deferred_ = true;
340
341 return true;
342 } 194 }
343 195
344 void DownloadResourceHandler::OnResponseCompleted( 196 void DownloadResourceHandler::OnResponseCompleted(
345 const net::URLRequestStatus& status, 197 const net::URLRequestStatus& status,
346 const std::string& security_info, 198 const std::string& security_info,
347 bool* defer) { 199 bool* defer) {
348 DCHECK_CURRENTLY_ON(BrowserThread::IO); 200 DownloadInterruptReason result = core_.OnResponseCompleted(status);
349 int response_code = status.is_success() ? request()->GetResponseCode() : 0; 201 CallStartedCB(result);
350 DVLOG(20) << __FUNCTION__ << "()" << DebugString()
351 << " status.status() = " << status.status()
352 << " status.error() = " << status.error()
353 << " response_code = " << response_code;
354
355 net::Error error_code = net::OK;
356 if (status.status() == net::URLRequestStatus::FAILED ||
357 // Note cancels as failures too.
358 status.status() == net::URLRequestStatus::CANCELED) {
359 error_code = static_cast<net::Error>(status.error()); // Normal case.
360 // Make sure that at least the fact of failure comes through.
361 if (error_code == net::OK)
362 error_code = net::ERR_FAILED;
363 }
364
365 // ERR_CONTENT_LENGTH_MISMATCH and ERR_INCOMPLETE_CHUNKED_ENCODING are
366 // allowed since a number of servers in the wild close the connection too
367 // early by mistake. Other browsers - IE9, Firefox 11.0, and Safari 5.1.4 -
368 // treat downloads as complete in both cases, so we follow their lead.
369 if (error_code == net::ERR_CONTENT_LENGTH_MISMATCH ||
370 error_code == net::ERR_INCOMPLETE_CHUNKED_ENCODING) {
371 error_code = net::OK;
372 }
373 DownloadInterruptReason reason =
374 ConvertNetErrorToInterruptReason(
375 error_code, DOWNLOAD_INTERRUPT_FROM_NETWORK);
376
377 if (status.status() == net::URLRequestStatus::CANCELED &&
378 status.error() == net::ERR_ABORTED) {
379 // CANCELED + ERR_ABORTED == something outside of the network
380 // stack cancelled the request. There aren't that many things that
381 // could do this to a download request (whose lifetime is separated from
382 // the tab from which it came). We map this to USER_CANCELLED as the
383 // case we know about (system suspend because of laptop close) corresponds
384 // to a user action.
385 // TODO(ahendrickson) -- Find a better set of codes to use here, as
386 // CANCELED/ERR_ABORTED can occur for reasons other than user cancel.
387 if (net::IsCertStatusError(request()->ssl_info().cert_status))
388 reason = DOWNLOAD_INTERRUPT_REASON_SERVER_CERT_PROBLEM;
389 else
390 reason = DOWNLOAD_INTERRUPT_REASON_USER_CANCELED;
391 }
392
393 if (status.is_success() &&
394 reason == DOWNLOAD_INTERRUPT_REASON_NONE &&
395 request()->response_headers()) {
396 // Handle server's response codes.
397 switch(response_code) {
398 case -1: // Non-HTTP request.
399 case net::HTTP_OK:
400 case net::HTTP_CREATED:
401 case net::HTTP_ACCEPTED:
402 case net::HTTP_NON_AUTHORITATIVE_INFORMATION:
403 case net::HTTP_RESET_CONTENT:
404 case net::HTTP_PARTIAL_CONTENT:
405 // Expected successful codes.
406 break;
407 case net::HTTP_NO_CONTENT:
408 case net::HTTP_NOT_FOUND:
409 reason = DOWNLOAD_INTERRUPT_REASON_SERVER_BAD_CONTENT;
410 break;
411 case net::HTTP_REQUESTED_RANGE_NOT_SATISFIABLE:
412 // Retry by downloading from the start automatically:
413 // If we haven't received data when we get this error, we won't.
414 reason = DOWNLOAD_INTERRUPT_REASON_SERVER_NO_RANGE;
415 break;
416 case net::HTTP_UNAUTHORIZED:
417 // Server didn't authorize this request.
418 reason = DOWNLOAD_INTERRUPT_REASON_SERVER_UNAUTHORIZED;
419 break;
420 case net::HTTP_FORBIDDEN:
421 // Server forbids access to this resource.
422 reason = DOWNLOAD_INTERRUPT_REASON_SERVER_FORBIDDEN;
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_SPARSE_SLOWLY("Download.MapErrorNetworkFailed",
457 std::abs(status.error()));
458 }
459
460 stream_writer_.reset(); // We no longer need the stream.
461 read_buffer_ = NULL;
462 } 202 }
463 203
464 void DownloadResourceHandler::OnDataDownloaded(int bytes_downloaded) { 204 void DownloadResourceHandler::OnDataDownloaded(int bytes_downloaded) {
465 NOTREACHED(); 205 NOTREACHED();
466 } 206 }
467 207
468 void DownloadResourceHandler::PauseRequest() { 208 void DownloadResourceHandler::PauseRequest() {
469 DCHECK_CURRENTLY_ON(BrowserThread::IO); 209 core_.PauseRequest();
470
471 ++pause_count_;
472 } 210 }
473 211
474 void DownloadResourceHandler::ResumeRequest() { 212 void DownloadResourceHandler::ResumeRequest() {
213 core_.ResumeRequest();
214 }
215
216 void DownloadResourceHandler::OnCoreReadyToRead() {
475 DCHECK_CURRENTLY_ON(BrowserThread::IO); 217 DCHECK_CURRENTLY_ON(BrowserThread::IO);
476 DCHECK_LT(0, pause_count_);
477
478 --pause_count_;
479
480 if (!was_deferred_)
481 return;
482 if (pause_count_ > 0)
483 return;
484
485 was_deferred_ = false;
486 if (!last_stream_pause_time_.is_null()) {
487 total_pause_time_ += (base::TimeTicks::Now() - last_stream_pause_time_);
488 last_stream_pause_time_ = base::TimeTicks();
489 }
490
491 controller()->Resume(); 218 controller()->Resume();
492 } 219 }
493 220
494 void DownloadResourceHandler::CancelRequest() { 221 void DownloadResourceHandler::CancelRequest() {
495 DCHECK_CURRENTLY_ON(BrowserThread::IO); 222 DCHECK_CURRENTLY_ON(BrowserThread::IO);
496 223
497 const ResourceRequestInfoImpl* info = GetRequestInfo(); 224 const ResourceRequestInfoImpl* info = GetRequestInfo();
498 ResourceDispatcherHostImpl::Get()->CancelRequest( 225 ResourceDispatcherHostImpl::Get()->CancelRequest(
499 info->GetChildID(), 226 info->GetChildID(),
500 info->GetRequestID()); 227 info->GetRequestID());
(...skipping 11 matching lines...) Expand all
512 " }" 239 " }"
513 " }", 240 " }",
514 request() ? 241 request() ?
515 request()->url().spec().c_str() : 242 request()->url().spec().c_str() :
516 "<NULL request>", 243 "<NULL request>",
517 info->GetChildID(), 244 info->GetChildID(),
518 info->GetRequestID(), 245 info->GetRequestID(),
519 info->GetRouteID()); 246 info->GetRouteID());
520 } 247 }
521 248
522 DownloadResourceHandler::~DownloadResourceHandler() {
523 DCHECK_CURRENTLY_ON(BrowserThread::IO);
524
525 // This won't do anything if the callback was called before.
526 // If it goes through, it will likely be because OnWillStart() returned
527 // false somewhere in the chain of resource handlers.
528 CallStartedCB(NULL, DOWNLOAD_INTERRUPT_REASON_NETWORK_FAILED);
529
530 // Remove output stream callback if a stream exists.
531 if (stream_writer_)
532 stream_writer_->RegisterCallback(base::Closure());
533
534 // tab_info_ must be destroyed on UI thread, since
535 // InitializeDownloadTabInfoOnUIThread might still be using it.
536 if (tab_info_.get()) {
537 BrowserThread::PostTask(
538 BrowserThread::UI, FROM_HERE,
539 base::Bind(&DeleteOnUIThread, base::Passed(&tab_info_)));
540 }
541
542 UMA_HISTOGRAM_TIMES("SB2.DownloadDuration",
543 base::TimeTicks::Now() - download_start_time_);
544 }
545
546 } // namespace content 249 } // namespace content
OLDNEW
« no previous file with comments | « content/browser/download/download_resource_handler.h ('k') | content/browser/download/url_downloader.h » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698