1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "net/url_request/url_fetcher_core.h"
10 #include "base/logging.h"
11 #include "base/metrics/histogram.h"
12 #include "base/profiler/scoped_tracker.h"
13 #include "base/sequenced_task_runner.h"
14 #include "base/single_thread_task_runner.h"
15 #include "base/stl_util.h"
16 #include "base/thread_task_runner_handle.h"
17 #include "base/tracked_objects.h"
18 #include "net/base/elements_upload_data_stream.h"
19 #include "net/base/io_buffer.h"
20 #include "net/base/load_flags.h"
21 #include "net/base/net_errors.h"
22 #include "net/base/request_priority.h"
23 #include "net/base/upload_bytes_element_reader.h"
24 #include "net/base/upload_data_stream.h"
25 #include "net/base/upload_file_element_reader.h"
26 #include "net/http/http_response_headers.h"
27 #include "net/url_request/redirect_info.h"
28 #include "net/url_request/url_fetcher_delegate.h"
29 #include "net/url_request/url_fetcher_response_writer.h"
30 #include "net/url_request/url_request_context.h"
31 #include "net/url_request/url_request_context_getter.h"
32 #include "net/url_request/url_request_throttler_manager.h"
36 const int kBufferSize
= 4096;
37 const int kUploadProgressTimerInterval
= 100;
38 bool g_ignore_certificate_requests
= false;
40 void EmptyCompletionCallback(int result
) {}
46 // URLFetcherCore::Registry ---------------------------------------------------
48 URLFetcherCore::Registry::Registry() {}
49 URLFetcherCore::Registry::~Registry() {}
51 void URLFetcherCore::Registry::AddURLFetcherCore(URLFetcherCore
* core
) {
52 DCHECK(!ContainsKey(fetchers_
, core
));
53 fetchers_
.insert(core
);
56 void URLFetcherCore::Registry::RemoveURLFetcherCore(URLFetcherCore
* core
) {
57 DCHECK(ContainsKey(fetchers_
, core
));
58 fetchers_
.erase(core
);
61 void URLFetcherCore::Registry::CancelAll() {
62 while (!fetchers_
.empty())
63 (*fetchers_
.begin())->CancelURLRequest(ERR_ABORTED
);
66 // URLFetcherCore -------------------------------------------------------------
69 base::LazyInstance
<URLFetcherCore::Registry
>
70 URLFetcherCore::g_registry
= LAZY_INSTANCE_INITIALIZER
;
72 URLFetcherCore::URLFetcherCore(URLFetcher
* fetcher
,
73 const GURL
& original_url
,
74 URLFetcher::RequestType request_type
,
75 URLFetcherDelegate
* d
)
77 original_url_(original_url
),
78 request_type_(request_type
),
80 delegate_task_runner_(base::ThreadTaskRunnerHandle::Get()),
81 load_flags_(LOAD_NORMAL
),
82 response_code_(URLFetcher::RESPONSE_CODE_INVALID
),
83 buffer_(new IOBuffer(kBufferSize
)),
84 url_request_data_key_(NULL
),
85 was_fetched_via_proxy_(false),
86 upload_content_set_(false),
87 upload_range_offset_(0),
88 upload_range_length_(0),
90 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE
),
91 is_chunked_upload_(false),
92 was_cancelled_(false),
93 stop_on_redirect_(false),
94 stopped_on_redirect_(false),
95 automatically_retry_on_5xx_(true),
96 num_retries_on_5xx_(0),
97 max_retries_on_5xx_(0),
98 num_retries_on_network_changes_(0),
99 max_retries_on_network_changes_(0),
100 current_upload_bytes_(-1),
101 current_response_bytes_(0),
102 total_response_bytes_(-1) {
103 CHECK(original_url_
.is_valid());
106 void URLFetcherCore::Start() {
107 DCHECK(delegate_task_runner_
.get());
108 DCHECK(request_context_getter_
.get()) << "We need an URLRequestContext!";
109 if (network_task_runner_
.get()) {
110 DCHECK_EQ(network_task_runner_
,
111 request_context_getter_
->GetNetworkTaskRunner());
113 network_task_runner_
= request_context_getter_
->GetNetworkTaskRunner();
115 DCHECK(network_task_runner_
.get()) << "We need an IO task runner";
117 network_task_runner_
->PostTask(
118 FROM_HERE
, base::Bind(&URLFetcherCore::StartOnIOThread
, this));
121 void URLFetcherCore::Stop() {
122 if (delegate_task_runner_
.get()) // May be NULL in tests.
123 DCHECK(delegate_task_runner_
->BelongsToCurrentThread());
127 if (!network_task_runner_
.get())
129 if (network_task_runner_
->RunsTasksOnCurrentThread()) {
130 CancelURLRequest(ERR_ABORTED
);
132 network_task_runner_
->PostTask(
134 base::Bind(&URLFetcherCore::CancelURLRequest
, this, ERR_ABORTED
));
138 void URLFetcherCore::SetUploadData(const std::string
& upload_content_type
,
139 const std::string
& upload_content
) {
140 DCHECK(!is_chunked_upload_
);
141 DCHECK(!upload_content_set_
);
142 DCHECK(upload_content_
.empty());
143 DCHECK(upload_file_path_
.empty());
144 DCHECK(upload_content_type_
.empty());
146 // Empty |upload_content_type| is allowed iff the |upload_content| is empty.
147 DCHECK(upload_content
.empty() || !upload_content_type
.empty());
149 upload_content_type_
= upload_content_type
;
150 upload_content_
= upload_content
;
151 upload_content_set_
= true;
154 void URLFetcherCore::SetUploadFilePath(
155 const std::string
& upload_content_type
,
156 const base::FilePath
& file_path
,
159 scoped_refptr
<base::TaskRunner
> file_task_runner
) {
160 DCHECK(!is_chunked_upload_
);
161 DCHECK(!upload_content_set_
);
162 DCHECK(upload_content_
.empty());
163 DCHECK(upload_file_path_
.empty());
164 DCHECK_EQ(upload_range_offset_
, 0ULL);
165 DCHECK_EQ(upload_range_length_
, 0ULL);
166 DCHECK(upload_content_type_
.empty());
167 DCHECK(!upload_content_type
.empty());
169 upload_content_type_
= upload_content_type
;
170 upload_file_path_
= file_path
;
171 upload_range_offset_
= range_offset
;
172 upload_range_length_
= range_length
;
173 upload_file_task_runner_
= file_task_runner
;
174 upload_content_set_
= true;
177 void URLFetcherCore::SetChunkedUpload(const std::string
& content_type
) {
178 DCHECK(is_chunked_upload_
||
179 (upload_content_type_
.empty() &&
180 upload_content_
.empty()));
182 // Empty |content_type| is not allowed here, because it is impossible
183 // to ensure non-empty upload content as it is not yet supplied.
184 DCHECK(!content_type
.empty());
186 upload_content_type_
= content_type
;
187 upload_content_
.clear();
188 is_chunked_upload_
= true;
191 void URLFetcherCore::AppendChunkToUpload(const std::string
& content
,
192 bool is_last_chunk
) {
193 DCHECK(delegate_task_runner_
.get());
194 DCHECK(network_task_runner_
.get());
195 network_task_runner_
->PostTask(
197 base::Bind(&URLFetcherCore::CompleteAddingUploadDataChunk
, this, content
,
201 void URLFetcherCore::SetLoadFlags(int load_flags
) {
202 load_flags_
= load_flags
;
205 int URLFetcherCore::GetLoadFlags() const {
209 void URLFetcherCore::SetReferrer(const std::string
& referrer
) {
210 referrer_
= referrer
;
213 void URLFetcherCore::SetReferrerPolicy(
214 URLRequest::ReferrerPolicy referrer_policy
) {
215 referrer_policy_
= referrer_policy
;
218 void URLFetcherCore::SetExtraRequestHeaders(
219 const std::string
& extra_request_headers
) {
220 extra_request_headers_
.Clear();
221 extra_request_headers_
.AddHeadersFromString(extra_request_headers
);
224 void URLFetcherCore::AddExtraRequestHeader(const std::string
& header_line
) {
225 extra_request_headers_
.AddHeaderFromString(header_line
);
228 void URLFetcherCore::SetRequestContext(
229 URLRequestContextGetter
* request_context_getter
) {
230 DCHECK(!request_context_getter_
.get());
231 DCHECK(request_context_getter
);
232 request_context_getter_
= request_context_getter
;
235 void URLFetcherCore::SetFirstPartyForCookies(
236 const GURL
& first_party_for_cookies
) {
237 DCHECK(first_party_for_cookies_
.is_empty());
238 first_party_for_cookies_
= first_party_for_cookies
;
241 void URLFetcherCore::SetURLRequestUserData(
243 const URLFetcher::CreateDataCallback
& create_data_callback
) {
245 DCHECK(!create_data_callback
.is_null());
246 url_request_data_key_
= key
;
247 url_request_create_data_callback_
= create_data_callback
;
250 void URLFetcherCore::SetStopOnRedirect(bool stop_on_redirect
) {
251 stop_on_redirect_
= stop_on_redirect
;
254 void URLFetcherCore::SetAutomaticallyRetryOn5xx(bool retry
) {
255 automatically_retry_on_5xx_
= retry
;
258 void URLFetcherCore::SetMaxRetriesOn5xx(int max_retries
) {
259 max_retries_on_5xx_
= max_retries
;
262 int URLFetcherCore::GetMaxRetriesOn5xx() const {
263 return max_retries_on_5xx_
;
266 base::TimeDelta
URLFetcherCore::GetBackoffDelay() const {
267 return backoff_delay_
;
270 void URLFetcherCore::SetAutomaticallyRetryOnNetworkChanges(int max_retries
) {
271 max_retries_on_network_changes_
= max_retries
;
274 void URLFetcherCore::SaveResponseToFileAtPath(
275 const base::FilePath
& file_path
,
276 scoped_refptr
<base::SequencedTaskRunner
> file_task_runner
) {
277 DCHECK(delegate_task_runner_
->BelongsToCurrentThread());
278 SaveResponseWithWriter(scoped_ptr
<URLFetcherResponseWriter
>(
279 new URLFetcherFileWriter(file_task_runner
, file_path
)));
282 void URLFetcherCore::SaveResponseToTemporaryFile(
283 scoped_refptr
<base::SequencedTaskRunner
> file_task_runner
) {
284 DCHECK(delegate_task_runner_
->BelongsToCurrentThread());
285 SaveResponseWithWriter(scoped_ptr
<URLFetcherResponseWriter
>(
286 new URLFetcherFileWriter(file_task_runner
, base::FilePath())));
289 void URLFetcherCore::SaveResponseWithWriter(
290 scoped_ptr
<URLFetcherResponseWriter
> response_writer
) {
291 DCHECK(delegate_task_runner_
->BelongsToCurrentThread());
292 response_writer_
= response_writer
.Pass();
295 HttpResponseHeaders
* URLFetcherCore::GetResponseHeaders() const {
296 return response_headers_
.get();
299 // TODO(panayiotis): socket_address_ is written in the IO thread,
300 // if this is accessed in the UI thread, this could result in a race.
301 // Same for response_headers_ above and was_fetched_via_proxy_ below.
302 HostPortPair
URLFetcherCore::GetSocketAddress() const {
303 return socket_address_
;
306 bool URLFetcherCore::WasFetchedViaProxy() const {
307 return was_fetched_via_proxy_
;
310 const GURL
& URLFetcherCore::GetOriginalURL() const {
311 return original_url_
;
314 const GURL
& URLFetcherCore::GetURL() const {
318 const URLRequestStatus
& URLFetcherCore::GetStatus() const {
322 int URLFetcherCore::GetResponseCode() const {
323 return response_code_
;
326 const ResponseCookies
& URLFetcherCore::GetCookies() const {
330 void URLFetcherCore::ReceivedContentWasMalformed() {
331 DCHECK(delegate_task_runner_
->BelongsToCurrentThread());
332 if (network_task_runner_
.get()) {
333 network_task_runner_
->PostTask(
334 FROM_HERE
, base::Bind(&URLFetcherCore::NotifyMalformedContent
, this));
338 bool URLFetcherCore::GetResponseAsString(
339 std::string
* out_response_string
) const {
340 URLFetcherStringWriter
* string_writer
=
341 response_writer_
? response_writer_
->AsStringWriter() : NULL
;
345 *out_response_string
= string_writer
->data();
346 UMA_HISTOGRAM_MEMORY_KB("UrlFetcher.StringResponseSize",
347 (string_writer
->data().length() / 1024));
351 bool URLFetcherCore::GetResponseAsFilePath(bool take_ownership
,
352 base::FilePath
* out_response_path
) {
353 DCHECK(delegate_task_runner_
->BelongsToCurrentThread());
355 URLFetcherFileWriter
* file_writer
=
356 response_writer_
? response_writer_
->AsFileWriter() : NULL
;
360 *out_response_path
= file_writer
->file_path();
362 if (take_ownership
) {
363 // Intentionally calling a file_writer_ method directly without posting
364 // the task to network_task_runner_.
366 // This is for correctly handling the case when file_writer_->DisownFile()
367 // is soon followed by URLFetcherCore::Stop(). We have to make sure that
368 // DisownFile takes effect before Stop deletes file_writer_.
370 // This direct call should be thread-safe, since DisownFile itself does no
371 // file operation. It just flips the state to be referred in destruction.
372 file_writer
->DisownFile();
377 void URLFetcherCore::OnReceivedRedirect(URLRequest
* request
,
378 const RedirectInfo
& redirect_info
,
379 bool* defer_redirect
) {
380 DCHECK_EQ(request
, request_
.get());
381 DCHECK(network_task_runner_
->BelongsToCurrentThread());
382 if (stop_on_redirect_
) {
383 stopped_on_redirect_
= true;
384 url_
= redirect_info
.new_url
;
385 response_code_
= request_
->GetResponseCode();
386 was_fetched_via_proxy_
= request_
->was_fetched_via_proxy();
388 OnReadCompleted(request
, 0);
392 void URLFetcherCore::OnResponseStarted(URLRequest
* request
) {
393 // TODO(vadimt): Remove ScopedTracker below once crbug.com/423948 is fixed.
394 tracked_objects::ScopedTracker
tracking_profile(
395 FROM_HERE_WITH_EXPLICIT_FUNCTION(
396 "423948 URLFetcherCore::OnResponseStarted"));
398 DCHECK_EQ(request
, request_
.get());
399 DCHECK(network_task_runner_
->BelongsToCurrentThread());
400 if (request_
->status().is_success()) {
401 response_code_
= request_
->GetResponseCode();
402 response_headers_
= request_
->response_headers();
403 socket_address_
= request_
->GetSocketAddress();
404 was_fetched_via_proxy_
= request_
->was_fetched_via_proxy();
405 total_response_bytes_
= request_
->GetExpectedContentSize();
411 void URLFetcherCore::OnCertificateRequested(
413 SSLCertRequestInfo
* cert_request_info
) {
414 DCHECK_EQ(request
, request_
.get());
415 DCHECK(network_task_runner_
->BelongsToCurrentThread());
417 if (g_ignore_certificate_requests
) {
418 request
->ContinueWithCertificate(NULL
);
424 void URLFetcherCore::OnReadCompleted(URLRequest
* request
,
426 // TODO(vadimt): Remove ScopedTracker below once crbug.com/423948 is fixed.
427 tracked_objects::ScopedTracker
tracking_profile(
428 FROM_HERE_WITH_EXPLICIT_FUNCTION(
429 "423948 URLFetcherCore::OnReadCompleted"));
431 DCHECK(request
== request_
);
432 DCHECK(network_task_runner_
->BelongsToCurrentThread());
434 if (!stopped_on_redirect_
)
435 url_
= request
->url();
436 URLRequestThrottlerManager
* throttler_manager
=
437 request
->context()->throttler_manager();
438 if (throttler_manager
) {
439 url_throttler_entry_
= throttler_manager
->RegisterRequestUrl(url_
);
443 if (!request_
->status().is_success() || bytes_read
<= 0)
446 current_response_bytes_
+= bytes_read
;
447 InformDelegateDownloadProgress();
450 WriteBuffer(new DrainableIOBuffer(buffer_
.get(), bytes_read
));
452 // Write failed or waiting for write completion.
455 } while (request_
->Read(buffer_
.get(), kBufferSize
, &bytes_read
));
457 const URLRequestStatus status
= request_
->status();
459 if (status
.is_success())
460 request_
->GetResponseCookies(&cookies_
);
462 // See comments re: HEAD requests in ReadResponse().
463 if (!status
.is_io_pending() || request_type_
== URLFetcher::HEAD
) {
467 // No more data to write.
468 const int result
= response_writer_
->Finish(
469 base::Bind(&URLFetcherCore::DidFinishWriting
, this));
470 if (result
!= ERR_IO_PENDING
)
471 DidFinishWriting(result
);
475 void URLFetcherCore::CancelAll() {
476 g_registry
.Get().CancelAll();
479 int URLFetcherCore::GetNumFetcherCores() {
480 return g_registry
.Get().size();
483 void URLFetcherCore::SetIgnoreCertificateRequests(bool ignored
) {
484 g_ignore_certificate_requests
= ignored
;
487 URLFetcherCore::~URLFetcherCore() {
488 // |request_| should be NULL. If not, it's unsafe to delete it here since we
489 // may not be on the IO thread.
490 DCHECK(!request_
.get());
493 void URLFetcherCore::StartOnIOThread() {
494 DCHECK(network_task_runner_
->BelongsToCurrentThread());
496 if (!response_writer_
)
497 response_writer_
.reset(new URLFetcherStringWriter
);
499 const int result
= response_writer_
->Initialize(
500 base::Bind(&URLFetcherCore::DidInitializeWriter
, this));
501 if (result
!= ERR_IO_PENDING
)
502 DidInitializeWriter(result
);
505 void URLFetcherCore::StartURLRequest() {
506 DCHECK(network_task_runner_
->BelongsToCurrentThread());
508 if (was_cancelled_
) {
509 // Since StartURLRequest() is posted as a *delayed* task, it may
510 // run after the URLFetcher was already stopped.
514 DCHECK(request_context_getter_
.get());
515 DCHECK(!request_
.get());
517 g_registry
.Get().AddURLFetcherCore(this);
518 current_response_bytes_
= 0;
519 request_
= request_context_getter_
->GetURLRequestContext()->CreateRequest(
520 original_url_
, DEFAULT_PRIORITY
, this, NULL
);
521 request_
->set_stack_trace(stack_trace_
);
522 int flags
= request_
->load_flags() | load_flags_
;
524 if (is_chunked_upload_
)
525 request_
->EnableChunkedUpload();
526 request_
->SetLoadFlags(flags
);
527 request_
->SetReferrer(referrer_
);
528 request_
->set_referrer_policy(referrer_policy_
);
529 request_
->set_first_party_for_cookies(first_party_for_cookies_
.is_empty() ?
530 original_url_
: first_party_for_cookies_
);
531 if (url_request_data_key_
&& !url_request_create_data_callback_
.is_null()) {
532 request_
->SetUserData(url_request_data_key_
,
533 url_request_create_data_callback_
.Run());
536 switch (request_type_
) {
537 case URLFetcher::GET
:
540 case URLFetcher::POST
:
541 case URLFetcher::PUT
:
542 case URLFetcher::PATCH
:
543 // Upload content must be set.
544 DCHECK(is_chunked_upload_
|| upload_content_set_
);
546 request_
->set_method(
547 request_type_
== URLFetcher::POST
? "POST" :
548 request_type_
== URLFetcher::PUT
? "PUT" : "PATCH");
549 if (!upload_content_type_
.empty()) {
550 extra_request_headers_
.SetHeader(HttpRequestHeaders::kContentType
,
551 upload_content_type_
);
553 if (!upload_content_
.empty()) {
554 scoped_ptr
<UploadElementReader
> reader(new UploadBytesElementReader(
555 upload_content_
.data(), upload_content_
.size()));
556 request_
->set_upload(
557 ElementsUploadDataStream::CreateWithReader(reader
.Pass(), 0));
558 } else if (!upload_file_path_
.empty()) {
559 scoped_ptr
<UploadElementReader
> reader(
560 new UploadFileElementReader(upload_file_task_runner_
.get(),
562 upload_range_offset_
,
563 upload_range_length_
,
565 request_
->set_upload(
566 ElementsUploadDataStream::CreateWithReader(reader
.Pass(), 0));
569 current_upload_bytes_
= -1;
570 // TODO(kinaba): http://crbug.com/118103. Implement upload callback in the
571 // layer and avoid using timer here.
572 upload_progress_checker_timer_
.reset(
573 new base::RepeatingTimer
<URLFetcherCore
>());
574 upload_progress_checker_timer_
->Start(
576 base::TimeDelta::FromMilliseconds(kUploadProgressTimerInterval
),
578 &URLFetcherCore::InformDelegateUploadProgress
);
581 case URLFetcher::HEAD
:
582 request_
->set_method("HEAD");
585 case URLFetcher::DELETE_REQUEST
:
586 request_
->set_method("DELETE");
593 if (!extra_request_headers_
.IsEmpty())
594 request_
->SetExtraRequestHeaders(extra_request_headers_
);
599 void URLFetcherCore::DidInitializeWriter(int result
) {
601 CancelURLRequest(result
);
602 delegate_task_runner_
->PostTask(
604 base::Bind(&URLFetcherCore::InformDelegateFetchIsComplete
, this));
607 StartURLRequestWhenAppropriate();
610 void URLFetcherCore::StartURLRequestWhenAppropriate() {
611 DCHECK(network_task_runner_
->BelongsToCurrentThread());
616 DCHECK(request_context_getter_
.get());
618 int64 delay
= INT64_C(0);
619 if (!original_url_throttler_entry_
.get()) {
620 URLRequestThrottlerManager
* manager
=
621 request_context_getter_
->GetURLRequestContext()->throttler_manager();
623 original_url_throttler_entry_
=
624 manager
->RegisterRequestUrl(original_url_
);
627 if (original_url_throttler_entry_
.get()) {
628 delay
= original_url_throttler_entry_
->ReserveSendingTimeForNextRequest(
629 GetBackoffReleaseTime());
632 if (delay
== INT64_C(0)) {
635 base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
636 FROM_HERE
, base::Bind(&URLFetcherCore::StartURLRequest
, this),
637 base::TimeDelta::FromMilliseconds(delay
));
641 void URLFetcherCore::CancelURLRequest(int error
) {
642 DCHECK(network_task_runner_
->BelongsToCurrentThread());
644 if (request_
.get()) {
645 request_
->CancelWithError(error
);
649 // Set the error manually.
650 // Normally, calling URLRequest::CancelWithError() results in calling
651 // OnReadCompleted() with bytes_read = -1 via an asynchronous task posted by
652 // URLRequestJob::NotifyDone(). But, because the request was released
653 // immediately after being canceled, the request could not call
654 // OnReadCompleted() which overwrites |status_| with the error status.
655 status_
.set_status(URLRequestStatus::CANCELED
);
656 status_
.set_error(error
);
658 // Release the reference to the request context. There could be multiple
659 // references to URLFetcher::Core at this point so it may take a while to
660 // delete the object, but we cannot delay the destruction of the request
662 request_context_getter_
= NULL
;
663 first_party_for_cookies_
= GURL();
664 url_request_data_key_
= NULL
;
665 url_request_create_data_callback_
.Reset();
666 was_cancelled_
= true;
669 void URLFetcherCore::OnCompletedURLRequest(
670 base::TimeDelta backoff_delay
) {
671 DCHECK(delegate_task_runner_
->BelongsToCurrentThread());
673 // Save the status and backoff_delay so that delegates can read it.
675 backoff_delay_
= backoff_delay
;
676 InformDelegateFetchIsComplete();
680 void URLFetcherCore::InformDelegateFetchIsComplete() {
681 DCHECK(delegate_task_runner_
->BelongsToCurrentThread());
683 delegate_
->OnURLFetchComplete(fetcher_
);
686 void URLFetcherCore::NotifyMalformedContent() {
687 DCHECK(network_task_runner_
->BelongsToCurrentThread());
688 if (url_throttler_entry_
.get()) {
689 int status_code
= response_code_
;
690 if (status_code
== URLFetcher::RESPONSE_CODE_INVALID
) {
691 // The status code will generally be known by the time clients
692 // call the |ReceivedContentWasMalformed()| function (which ends up
693 // calling the current function) but if it's not, we need to assume
694 // the response was successful so that the total failure count
695 // used to calculate exponential back-off goes up.
698 url_throttler_entry_
->ReceivedContentWasMalformed(status_code
);
702 void URLFetcherCore::DidFinishWriting(int result
) {
704 CancelURLRequest(result
);
705 delegate_task_runner_
->PostTask(
707 base::Bind(&URLFetcherCore::InformDelegateFetchIsComplete
, this));
710 // If the file was successfully closed, then the URL request is complete.
711 RetryOrCompleteUrlFetch();
714 void URLFetcherCore::RetryOrCompleteUrlFetch() {
715 DCHECK(network_task_runner_
->BelongsToCurrentThread());
716 base::TimeDelta backoff_delay
;
718 // Checks the response from server.
719 if (response_code_
>= 500 ||
720 status_
.error() == ERR_TEMPORARILY_THROTTLED
) {
721 // When encountering a server error, we will send the request again
722 // after backoff time.
723 ++num_retries_on_5xx_
;
725 // Note that backoff_delay may be 0 because (a) the
726 // URLRequestThrottlerManager and related code does not
727 // necessarily back off on the first error, (b) it only backs off
728 // on some of the 5xx status codes, (c) not all URLRequestContexts
729 // have a throttler manager.
730 base::TimeTicks backoff_release_time
= GetBackoffReleaseTime();
731 backoff_delay
= backoff_release_time
- base::TimeTicks::Now();
732 if (backoff_delay
< base::TimeDelta())
733 backoff_delay
= base::TimeDelta();
735 if (automatically_retry_on_5xx_
&&
736 num_retries_on_5xx_
<= max_retries_on_5xx_
) {
741 backoff_delay
= base::TimeDelta();
744 // Retry if the request failed due to network changes.
745 if (status_
.error() == ERR_NETWORK_CHANGED
&&
746 num_retries_on_network_changes_
< max_retries_on_network_changes_
) {
747 ++num_retries_on_network_changes_
;
749 // Retry soon, after flushing all the current tasks which may include
750 // further network change observers.
751 network_task_runner_
->PostTask(
752 FROM_HERE
, base::Bind(&URLFetcherCore::StartOnIOThread
, this));
756 request_context_getter_
= NULL
;
757 first_party_for_cookies_
= GURL();
758 url_request_data_key_
= NULL
;
759 url_request_create_data_callback_
.Reset();
760 bool posted
= delegate_task_runner_
->PostTask(
762 base::Bind(&URLFetcherCore::OnCompletedURLRequest
, this, backoff_delay
));
764 // If the delegate message loop does not exist any more, then the delegate
765 // should be gone too.
766 DCHECK(posted
|| !delegate_
);
769 void URLFetcherCore::ReleaseRequest() {
770 upload_progress_checker_timer_
.reset();
772 g_registry
.Get().RemoveURLFetcherCore(this);
775 base::TimeTicks
URLFetcherCore::GetBackoffReleaseTime() {
776 DCHECK(network_task_runner_
->BelongsToCurrentThread());
778 if (!original_url_throttler_entry_
.get())
779 return base::TimeTicks();
781 base::TimeTicks original_url_backoff
=
782 original_url_throttler_entry_
->GetExponentialBackoffReleaseTime();
783 base::TimeTicks destination_url_backoff
;
784 if (url_throttler_entry_
.get() &&
785 original_url_throttler_entry_
.get() != url_throttler_entry_
.get()) {
786 destination_url_backoff
=
787 url_throttler_entry_
->GetExponentialBackoffReleaseTime();
790 return original_url_backoff
> destination_url_backoff
?
791 original_url_backoff
: destination_url_backoff
;
794 void URLFetcherCore::CompleteAddingUploadDataChunk(
795 const std::string
& content
, bool is_last_chunk
) {
796 if (was_cancelled_
) {
797 // Since CompleteAddingUploadDataChunk() is posted as a *delayed* task, it
798 // may run after the URLFetcher was already stopped.
801 DCHECK(is_chunked_upload_
);
802 DCHECK(request_
.get());
803 DCHECK(!content
.empty());
804 request_
->AppendChunkToUpload(content
.data(),
805 static_cast<int>(content
.length()),
809 int URLFetcherCore::WriteBuffer(scoped_refptr
<DrainableIOBuffer
> data
) {
810 while (data
->BytesRemaining() > 0) {
811 const int result
= response_writer_
->Write(
813 data
->BytesRemaining(),
814 base::Bind(&URLFetcherCore::DidWriteBuffer
, this, data
));
816 if (result
!= ERR_IO_PENDING
)
817 DidWriteBuffer(data
, result
);
820 data
->DidConsume(result
);
825 void URLFetcherCore::DidWriteBuffer(scoped_refptr
<DrainableIOBuffer
> data
,
827 if (result
< 0) { // Handle errors.
828 CancelURLRequest(result
);
829 response_writer_
->Finish(base::Bind(&EmptyCompletionCallback
));
830 delegate_task_runner_
->PostTask(
832 base::Bind(&URLFetcherCore::InformDelegateFetchIsComplete
, this));
837 data
->DidConsume(result
);
838 if (WriteBuffer(data
) < 0)
841 // Finished writing buffer_. Read some more, unless the request has been
842 // cancelled and deleted.
843 DCHECK_EQ(0, data
->BytesRemaining());
848 void URLFetcherCore::ReadResponse() {
849 // Some servers may treat HEAD requests as GET requests. To free up the
850 // network connection as soon as possible, signal that the request has
851 // completed immediately, without trying to read any data back (all we care
852 // about is the response code and headers, which we already have).
854 if (request_
->status().is_success() &&
855 (request_type_
!= URLFetcher::HEAD
)) {
856 if (!request_
->Read(buffer_
.get(), kBufferSize
, &bytes_read
))
857 bytes_read
= -1; // Match OnReadCompleted() interface contract.
859 OnReadCompleted(request_
.get(), bytes_read
);
862 void URLFetcherCore::InformDelegateUploadProgress() {
863 DCHECK(network_task_runner_
->BelongsToCurrentThread());
864 if (request_
.get()) {
865 int64 current
= request_
->GetUploadProgress().position();
866 if (current_upload_bytes_
!= current
) {
867 current_upload_bytes_
= current
;
869 if (!is_chunked_upload_
) {
870 total
= static_cast<int64
>(request_
->GetUploadProgress().size());
871 // Total may be zero if the UploadDataStream::Init has not been called
872 // yet. Don't send the upload progress until the size is initialized.
876 delegate_task_runner_
->PostTask(
879 &URLFetcherCore::InformDelegateUploadProgressInDelegateThread
,
880 this, current
, total
));
885 void URLFetcherCore::InformDelegateUploadProgressInDelegateThread(
886 int64 current
, int64 total
) {
887 DCHECK(delegate_task_runner_
->BelongsToCurrentThread());
889 delegate_
->OnURLFetchUploadProgress(fetcher_
, current
, total
);
892 void URLFetcherCore::InformDelegateDownloadProgress() {
893 DCHECK(network_task_runner_
->BelongsToCurrentThread());
894 delegate_task_runner_
->PostTask(
897 &URLFetcherCore::InformDelegateDownloadProgressInDelegateThread
,
898 this, current_response_bytes_
, total_response_bytes_
));
901 void URLFetcherCore::InformDelegateDownloadProgressInDelegateThread(
902 int64 current
, int64 total
) {
903 DCHECK(delegate_task_runner_
->BelongsToCurrentThread());
905 delegate_
->OnURLFetchDownloadProgress(fetcher_
, current
, total
);