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 AssertHasNoUploadData();
141 DCHECK(!is_chunked_upload_
);
142 DCHECK(upload_content_type_
.empty());
144 // Empty |upload_content_type| is allowed iff the |upload_content| is empty.
145 DCHECK(upload_content
.empty() || !upload_content_type
.empty());
147 upload_content_type_
= upload_content_type
;
148 upload_content_
= upload_content
;
149 upload_content_set_
= true;
152 void URLFetcherCore::SetUploadFilePath(
153 const std::string
& upload_content_type
,
154 const base::FilePath
& file_path
,
157 scoped_refptr
<base::TaskRunner
> file_task_runner
) {
158 AssertHasNoUploadData();
159 DCHECK(!is_chunked_upload_
);
160 DCHECK_EQ(upload_range_offset_
, 0ULL);
161 DCHECK_EQ(upload_range_length_
, 0ULL);
162 DCHECK(upload_content_type_
.empty());
163 DCHECK(!upload_content_type
.empty());
165 upload_content_type_
= upload_content_type
;
166 upload_file_path_
= file_path
;
167 upload_range_offset_
= range_offset
;
168 upload_range_length_
= range_length
;
169 upload_file_task_runner_
= file_task_runner
;
170 upload_content_set_
= true;
173 void URLFetcherCore::SetUploadStreamFactory(
174 const std::string
& upload_content_type
,
175 const URLFetcher::CreateUploadStreamCallback
& factory
) {
176 AssertHasNoUploadData();
177 DCHECK(!is_chunked_upload_
);
178 DCHECK(upload_content_type_
.empty());
180 upload_content_type_
= upload_content_type
;
181 upload_stream_factory_
= factory
;
182 upload_content_set_
= true;
185 void URLFetcherCore::SetChunkedUpload(const std::string
& content_type
) {
186 if (!is_chunked_upload_
) {
187 AssertHasNoUploadData();
188 DCHECK(upload_content_type_
.empty());
191 // Empty |content_type| is not allowed here, because it is impossible
192 // to ensure non-empty upload content as it is not yet supplied.
193 DCHECK(!content_type
.empty());
195 upload_content_type_
= content_type
;
196 upload_content_
.clear();
197 is_chunked_upload_
= true;
200 void URLFetcherCore::AppendChunkToUpload(const std::string
& content
,
201 bool is_last_chunk
) {
202 DCHECK(delegate_task_runner_
.get());
203 DCHECK(network_task_runner_
.get());
204 network_task_runner_
->PostTask(
206 base::Bind(&URLFetcherCore::CompleteAddingUploadDataChunk
, this, content
,
210 void URLFetcherCore::SetLoadFlags(int load_flags
) {
211 load_flags_
= load_flags
;
214 int URLFetcherCore::GetLoadFlags() const {
218 void URLFetcherCore::SetReferrer(const std::string
& referrer
) {
219 referrer_
= referrer
;
222 void URLFetcherCore::SetReferrerPolicy(
223 URLRequest::ReferrerPolicy referrer_policy
) {
224 referrer_policy_
= referrer_policy
;
227 void URLFetcherCore::SetExtraRequestHeaders(
228 const std::string
& extra_request_headers
) {
229 extra_request_headers_
.Clear();
230 extra_request_headers_
.AddHeadersFromString(extra_request_headers
);
233 void URLFetcherCore::AddExtraRequestHeader(const std::string
& header_line
) {
234 extra_request_headers_
.AddHeaderFromString(header_line
);
237 void URLFetcherCore::SetRequestContext(
238 URLRequestContextGetter
* request_context_getter
) {
239 DCHECK(!request_context_getter_
.get());
240 DCHECK(request_context_getter
);
241 request_context_getter_
= request_context_getter
;
244 void URLFetcherCore::SetFirstPartyForCookies(
245 const GURL
& first_party_for_cookies
) {
246 DCHECK(first_party_for_cookies_
.is_empty());
247 first_party_for_cookies_
= first_party_for_cookies
;
250 void URLFetcherCore::SetURLRequestUserData(
252 const URLFetcher::CreateDataCallback
& create_data_callback
) {
254 DCHECK(!create_data_callback
.is_null());
255 url_request_data_key_
= key
;
256 url_request_create_data_callback_
= create_data_callback
;
259 void URLFetcherCore::SetStopOnRedirect(bool stop_on_redirect
) {
260 stop_on_redirect_
= stop_on_redirect
;
263 void URLFetcherCore::SetAutomaticallyRetryOn5xx(bool retry
) {
264 automatically_retry_on_5xx_
= retry
;
267 void URLFetcherCore::SetMaxRetriesOn5xx(int max_retries
) {
268 max_retries_on_5xx_
= max_retries
;
271 int URLFetcherCore::GetMaxRetriesOn5xx() const {
272 return max_retries_on_5xx_
;
275 base::TimeDelta
URLFetcherCore::GetBackoffDelay() const {
276 return backoff_delay_
;
279 void URLFetcherCore::SetAutomaticallyRetryOnNetworkChanges(int max_retries
) {
280 max_retries_on_network_changes_
= max_retries
;
283 void URLFetcherCore::SaveResponseToFileAtPath(
284 const base::FilePath
& file_path
,
285 scoped_refptr
<base::SequencedTaskRunner
> file_task_runner
) {
286 DCHECK(delegate_task_runner_
->BelongsToCurrentThread());
287 SaveResponseWithWriter(scoped_ptr
<URLFetcherResponseWriter
>(
288 new URLFetcherFileWriter(file_task_runner
, file_path
)));
291 void URLFetcherCore::SaveResponseToTemporaryFile(
292 scoped_refptr
<base::SequencedTaskRunner
> file_task_runner
) {
293 DCHECK(delegate_task_runner_
->BelongsToCurrentThread());
294 SaveResponseWithWriter(scoped_ptr
<URLFetcherResponseWriter
>(
295 new URLFetcherFileWriter(file_task_runner
, base::FilePath())));
298 void URLFetcherCore::SaveResponseWithWriter(
299 scoped_ptr
<URLFetcherResponseWriter
> response_writer
) {
300 DCHECK(delegate_task_runner_
->BelongsToCurrentThread());
301 response_writer_
= response_writer
.Pass();
304 HttpResponseHeaders
* URLFetcherCore::GetResponseHeaders() const {
305 return response_headers_
.get();
308 // TODO(panayiotis): socket_address_ is written in the IO thread,
309 // if this is accessed in the UI thread, this could result in a race.
310 // Same for response_headers_ above and was_fetched_via_proxy_ below.
311 HostPortPair
URLFetcherCore::GetSocketAddress() const {
312 return socket_address_
;
315 bool URLFetcherCore::WasFetchedViaProxy() const {
316 return was_fetched_via_proxy_
;
319 const GURL
& URLFetcherCore::GetOriginalURL() const {
320 return original_url_
;
323 const GURL
& URLFetcherCore::GetURL() const {
327 const URLRequestStatus
& URLFetcherCore::GetStatus() const {
331 int URLFetcherCore::GetResponseCode() const {
332 return response_code_
;
335 const ResponseCookies
& URLFetcherCore::GetCookies() const {
339 void URLFetcherCore::ReceivedContentWasMalformed() {
340 DCHECK(delegate_task_runner_
->BelongsToCurrentThread());
341 if (network_task_runner_
.get()) {
342 network_task_runner_
->PostTask(
343 FROM_HERE
, base::Bind(&URLFetcherCore::NotifyMalformedContent
, this));
347 bool URLFetcherCore::GetResponseAsString(
348 std::string
* out_response_string
) const {
349 URLFetcherStringWriter
* string_writer
=
350 response_writer_
? response_writer_
->AsStringWriter() : NULL
;
354 *out_response_string
= string_writer
->data();
355 UMA_HISTOGRAM_MEMORY_KB("UrlFetcher.StringResponseSize",
356 (string_writer
->data().length() / 1024));
360 bool URLFetcherCore::GetResponseAsFilePath(bool take_ownership
,
361 base::FilePath
* out_response_path
) {
362 DCHECK(delegate_task_runner_
->BelongsToCurrentThread());
364 URLFetcherFileWriter
* file_writer
=
365 response_writer_
? response_writer_
->AsFileWriter() : NULL
;
369 *out_response_path
= file_writer
->file_path();
371 if (take_ownership
) {
372 // Intentionally calling a file_writer_ method directly without posting
373 // the task to network_task_runner_.
375 // This is for correctly handling the case when file_writer_->DisownFile()
376 // is soon followed by URLFetcherCore::Stop(). We have to make sure that
377 // DisownFile takes effect before Stop deletes file_writer_.
379 // This direct call should be thread-safe, since DisownFile itself does no
380 // file operation. It just flips the state to be referred in destruction.
381 file_writer
->DisownFile();
386 void URLFetcherCore::OnReceivedRedirect(URLRequest
* request
,
387 const RedirectInfo
& redirect_info
,
388 bool* defer_redirect
) {
389 DCHECK_EQ(request
, request_
.get());
390 DCHECK(network_task_runner_
->BelongsToCurrentThread());
391 if (stop_on_redirect_
) {
392 stopped_on_redirect_
= true;
393 url_
= redirect_info
.new_url
;
394 response_code_
= request_
->GetResponseCode();
395 was_fetched_via_proxy_
= request_
->was_fetched_via_proxy();
397 OnReadCompleted(request
, 0);
401 void URLFetcherCore::OnResponseStarted(URLRequest
* request
) {
402 DCHECK_EQ(request
, request_
.get());
403 DCHECK(network_task_runner_
->BelongsToCurrentThread());
404 if (request_
->status().is_success()) {
405 response_code_
= request_
->GetResponseCode();
406 response_headers_
= request_
->response_headers();
407 socket_address_
= request_
->GetSocketAddress();
408 was_fetched_via_proxy_
= request_
->was_fetched_via_proxy();
409 total_response_bytes_
= request_
->GetExpectedContentSize();
415 void URLFetcherCore::OnCertificateRequested(
417 SSLCertRequestInfo
* cert_request_info
) {
418 DCHECK_EQ(request
, request_
.get());
419 DCHECK(network_task_runner_
->BelongsToCurrentThread());
421 if (g_ignore_certificate_requests
) {
422 request
->ContinueWithCertificate(NULL
);
428 void URLFetcherCore::OnReadCompleted(URLRequest
* request
,
430 DCHECK(request
== request_
);
431 DCHECK(network_task_runner_
->BelongsToCurrentThread());
433 if (!stopped_on_redirect_
)
434 url_
= request
->url();
435 URLRequestThrottlerManager
* throttler_manager
=
436 request
->context()->throttler_manager();
437 if (throttler_manager
)
438 url_throttler_entry_
= throttler_manager
->RegisterRequestUrl(url_
);
441 if (!request_
->status().is_success() || bytes_read
<= 0)
444 current_response_bytes_
+= bytes_read
;
445 InformDelegateDownloadProgress();
448 WriteBuffer(new DrainableIOBuffer(buffer_
.get(), bytes_read
));
450 // Write failed or waiting for write completion.
453 } while (request_
->Read(buffer_
.get(), kBufferSize
, &bytes_read
));
455 const URLRequestStatus status
= request_
->status();
456 if (status
.is_success())
457 request_
->GetResponseCookies(&cookies_
);
459 // See comments re: HEAD requests in ReadResponse().
460 if (!status
.is_io_pending() || request_type_
== URLFetcher::HEAD
) {
464 // No more data to write.
465 const int result
= response_writer_
->Finish(
466 base::Bind(&URLFetcherCore::DidFinishWriting
, this));
467 if (result
!= ERR_IO_PENDING
)
468 DidFinishWriting(result
);
472 void URLFetcherCore::CancelAll() {
473 g_registry
.Get().CancelAll();
476 int URLFetcherCore::GetNumFetcherCores() {
477 return g_registry
.Get().size();
480 void URLFetcherCore::SetIgnoreCertificateRequests(bool ignored
) {
481 g_ignore_certificate_requests
= ignored
;
484 URLFetcherCore::~URLFetcherCore() {
485 // |request_| should be NULL. If not, it's unsafe to delete it here since we
486 // may not be on the IO thread.
487 DCHECK(!request_
.get());
490 void URLFetcherCore::StartOnIOThread() {
491 DCHECK(network_task_runner_
->BelongsToCurrentThread());
493 if (!response_writer_
)
494 response_writer_
.reset(new URLFetcherStringWriter
);
496 const int result
= response_writer_
->Initialize(
497 base::Bind(&URLFetcherCore::DidInitializeWriter
, this));
498 if (result
!= ERR_IO_PENDING
)
499 DidInitializeWriter(result
);
502 void URLFetcherCore::StartURLRequest() {
503 DCHECK(network_task_runner_
->BelongsToCurrentThread());
505 if (was_cancelled_
) {
506 // Since StartURLRequest() is posted as a *delayed* task, it may
507 // run after the URLFetcher was already stopped.
511 DCHECK(request_context_getter_
.get());
512 DCHECK(!request_
.get());
514 g_registry
.Get().AddURLFetcherCore(this);
515 current_response_bytes_
= 0;
516 request_
= request_context_getter_
->GetURLRequestContext()->CreateRequest(
517 original_url_
, DEFAULT_PRIORITY
, this);
518 request_
->set_stack_trace(stack_trace_
);
519 int flags
= request_
->load_flags() | load_flags_
;
521 if (is_chunked_upload_
)
522 request_
->EnableChunkedUpload();
523 request_
->SetLoadFlags(flags
);
524 request_
->SetReferrer(referrer_
);
525 request_
->set_referrer_policy(referrer_policy_
);
526 request_
->set_first_party_for_cookies(first_party_for_cookies_
.is_empty() ?
527 original_url_
: first_party_for_cookies_
);
528 if (url_request_data_key_
&& !url_request_create_data_callback_
.is_null()) {
529 request_
->SetUserData(url_request_data_key_
,
530 url_request_create_data_callback_
.Run());
533 switch (request_type_
) {
534 case URLFetcher::GET
:
537 case URLFetcher::POST
:
538 case URLFetcher::PUT
:
539 case URLFetcher::PATCH
: {
540 // Upload content must be set.
541 DCHECK(is_chunked_upload_
|| upload_content_set_
);
543 request_
->set_method(
544 request_type_
== URLFetcher::POST
? "POST" :
545 request_type_
== URLFetcher::PUT
? "PUT" : "PATCH");
546 if (!upload_content_type_
.empty()) {
547 extra_request_headers_
.SetHeader(HttpRequestHeaders::kContentType
,
548 upload_content_type_
);
550 if (!upload_content_
.empty()) {
551 scoped_ptr
<UploadElementReader
> reader(new UploadBytesElementReader(
552 upload_content_
.data(), upload_content_
.size()));
553 request_
->set_upload(
554 ElementsUploadDataStream::CreateWithReader(reader
.Pass(), 0));
555 } else if (!upload_file_path_
.empty()) {
556 scoped_ptr
<UploadElementReader
> reader(
557 new UploadFileElementReader(upload_file_task_runner_
.get(),
559 upload_range_offset_
,
560 upload_range_length_
,
562 request_
->set_upload(
563 ElementsUploadDataStream::CreateWithReader(reader
.Pass(), 0));
564 } else if (!upload_stream_factory_
.is_null()) {
565 scoped_ptr
<UploadDataStream
> stream
= upload_stream_factory_
.Run();
567 request_
->set_upload(stream
.Pass());
570 current_upload_bytes_
= -1;
571 // TODO(kinaba): http://crbug.com/118103. Implement upload callback in the
572 // layer and avoid using timer here.
573 upload_progress_checker_timer_
.reset(
574 new base::RepeatingTimer
<URLFetcherCore
>());
575 upload_progress_checker_timer_
->Start(
577 base::TimeDelta::FromMilliseconds(kUploadProgressTimerInterval
),
579 &URLFetcherCore::InformDelegateUploadProgress
);
583 case URLFetcher::HEAD
:
584 request_
->set_method("HEAD");
587 case URLFetcher::DELETE_REQUEST
:
588 request_
->set_method("DELETE");
595 if (!extra_request_headers_
.IsEmpty())
596 request_
->SetExtraRequestHeaders(extra_request_headers_
);
601 void URLFetcherCore::DidInitializeWriter(int result
) {
603 CancelURLRequest(result
);
604 delegate_task_runner_
->PostTask(
606 base::Bind(&URLFetcherCore::InformDelegateFetchIsComplete
, this));
609 StartURLRequestWhenAppropriate();
612 void URLFetcherCore::StartURLRequestWhenAppropriate() {
613 DCHECK(network_task_runner_
->BelongsToCurrentThread());
618 DCHECK(request_context_getter_
.get());
621 if (!original_url_throttler_entry_
.get()) {
622 URLRequestThrottlerManager
* manager
=
623 request_context_getter_
->GetURLRequestContext()->throttler_manager();
625 original_url_throttler_entry_
=
626 manager
->RegisterRequestUrl(original_url_
);
629 if (original_url_throttler_entry_
.get()) {
630 delay
= original_url_throttler_entry_
->ReserveSendingTimeForNextRequest(
631 GetBackoffReleaseTime());
637 base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
638 FROM_HERE
, base::Bind(&URLFetcherCore::StartURLRequest
, this),
639 base::TimeDelta::FromMilliseconds(delay
));
643 void URLFetcherCore::CancelURLRequest(int error
) {
644 DCHECK(network_task_runner_
->BelongsToCurrentThread());
646 if (request_
.get()) {
647 request_
->CancelWithError(error
);
651 // Set the error manually.
652 // Normally, calling URLRequest::CancelWithError() results in calling
653 // OnReadCompleted() with bytes_read = -1 via an asynchronous task posted by
654 // URLRequestJob::NotifyDone(). But, because the request was released
655 // immediately after being canceled, the request could not call
656 // OnReadCompleted() which overwrites |status_| with the error status.
657 status_
.set_status(URLRequestStatus::CANCELED
);
658 status_
.set_error(error
);
660 // Release the reference to the request context. There could be multiple
661 // references to URLFetcher::Core at this point so it may take a while to
662 // delete the object, but we cannot delay the destruction of the request
664 request_context_getter_
= NULL
;
665 first_party_for_cookies_
= GURL();
666 url_request_data_key_
= NULL
;
667 url_request_create_data_callback_
.Reset();
668 was_cancelled_
= true;
671 void URLFetcherCore::OnCompletedURLRequest(
672 base::TimeDelta backoff_delay
) {
673 DCHECK(delegate_task_runner_
->BelongsToCurrentThread());
675 // Save the status and backoff_delay so that delegates can read it.
677 backoff_delay_
= backoff_delay
;
678 InformDelegateFetchIsComplete();
682 void URLFetcherCore::InformDelegateFetchIsComplete() {
683 DCHECK(delegate_task_runner_
->BelongsToCurrentThread());
685 delegate_
->OnURLFetchComplete(fetcher_
);
688 void URLFetcherCore::NotifyMalformedContent() {
689 DCHECK(network_task_runner_
->BelongsToCurrentThread());
690 if (url_throttler_entry_
.get()) {
691 int status_code
= response_code_
;
692 if (status_code
== URLFetcher::RESPONSE_CODE_INVALID
) {
693 // The status code will generally be known by the time clients
694 // call the |ReceivedContentWasMalformed()| function (which ends up
695 // calling the current function) but if it's not, we need to assume
696 // the response was successful so that the total failure count
697 // used to calculate exponential back-off goes up.
700 url_throttler_entry_
->ReceivedContentWasMalformed(status_code
);
704 void URLFetcherCore::DidFinishWriting(int result
) {
706 CancelURLRequest(result
);
707 delegate_task_runner_
->PostTask(
709 base::Bind(&URLFetcherCore::InformDelegateFetchIsComplete
, this));
712 // If the file was successfully closed, then the URL request is complete.
713 RetryOrCompleteUrlFetch();
716 void URLFetcherCore::RetryOrCompleteUrlFetch() {
717 DCHECK(network_task_runner_
->BelongsToCurrentThread());
718 base::TimeDelta backoff_delay
;
720 // Checks the response from server.
721 if (response_code_
>= 500 ||
722 status_
.error() == ERR_TEMPORARILY_THROTTLED
) {
723 // When encountering a server error, we will send the request again
724 // after backoff time.
725 ++num_retries_on_5xx_
;
727 // Note that backoff_delay may be 0 because (a) the
728 // URLRequestThrottlerManager and related code does not
729 // necessarily back off on the first error, (b) it only backs off
730 // on some of the 5xx status codes, (c) not all URLRequestContexts
731 // have a throttler manager.
732 base::TimeTicks backoff_release_time
= GetBackoffReleaseTime();
733 backoff_delay
= backoff_release_time
- base::TimeTicks::Now();
734 if (backoff_delay
< base::TimeDelta())
735 backoff_delay
= base::TimeDelta();
737 if (automatically_retry_on_5xx_
&&
738 num_retries_on_5xx_
<= max_retries_on_5xx_
) {
743 backoff_delay
= base::TimeDelta();
746 // Retry if the request failed due to network changes.
747 if (status_
.error() == ERR_NETWORK_CHANGED
&&
748 num_retries_on_network_changes_
< max_retries_on_network_changes_
) {
749 ++num_retries_on_network_changes_
;
751 // Retry soon, after flushing all the current tasks which may include
752 // further network change observers.
753 network_task_runner_
->PostTask(
754 FROM_HERE
, base::Bind(&URLFetcherCore::StartOnIOThread
, this));
758 request_context_getter_
= NULL
;
759 first_party_for_cookies_
= GURL();
760 url_request_data_key_
= NULL
;
761 url_request_create_data_callback_
.Reset();
762 bool posted
= delegate_task_runner_
->PostTask(
764 base::Bind(&URLFetcherCore::OnCompletedURLRequest
, this, backoff_delay
));
766 // If the delegate message loop does not exist any more, then the delegate
767 // should be gone too.
768 DCHECK(posted
|| !delegate_
);
771 void URLFetcherCore::ReleaseRequest() {
772 upload_progress_checker_timer_
.reset();
774 g_registry
.Get().RemoveURLFetcherCore(this);
777 base::TimeTicks
URLFetcherCore::GetBackoffReleaseTime() {
778 DCHECK(network_task_runner_
->BelongsToCurrentThread());
780 if (!original_url_throttler_entry_
.get())
781 return base::TimeTicks();
783 base::TimeTicks original_url_backoff
=
784 original_url_throttler_entry_
->GetExponentialBackoffReleaseTime();
785 base::TimeTicks destination_url_backoff
;
786 if (url_throttler_entry_
.get() &&
787 original_url_throttler_entry_
.get() != url_throttler_entry_
.get()) {
788 destination_url_backoff
=
789 url_throttler_entry_
->GetExponentialBackoffReleaseTime();
792 return original_url_backoff
> destination_url_backoff
?
793 original_url_backoff
: destination_url_backoff
;
796 void URLFetcherCore::CompleteAddingUploadDataChunk(
797 const std::string
& content
, bool is_last_chunk
) {
798 if (was_cancelled_
) {
799 // Since CompleteAddingUploadDataChunk() is posted as a *delayed* task, it
800 // may run after the URLFetcher was already stopped.
803 DCHECK(is_chunked_upload_
);
804 DCHECK(request_
.get());
805 DCHECK(!content
.empty());
806 request_
->AppendChunkToUpload(content
.data(),
807 static_cast<int>(content
.length()),
811 int URLFetcherCore::WriteBuffer(scoped_refptr
<DrainableIOBuffer
> data
) {
812 while (data
->BytesRemaining() > 0) {
813 const int result
= response_writer_
->Write(
815 data
->BytesRemaining(),
816 base::Bind(&URLFetcherCore::DidWriteBuffer
, this, data
));
818 if (result
!= ERR_IO_PENDING
)
819 DidWriteBuffer(data
, result
);
822 data
->DidConsume(result
);
827 void URLFetcherCore::DidWriteBuffer(scoped_refptr
<DrainableIOBuffer
> data
,
829 if (result
< 0) { // Handle errors.
830 CancelURLRequest(result
);
831 response_writer_
->Finish(base::Bind(&EmptyCompletionCallback
));
832 delegate_task_runner_
->PostTask(
834 base::Bind(&URLFetcherCore::InformDelegateFetchIsComplete
, this));
839 data
->DidConsume(result
);
840 if (WriteBuffer(data
) < 0)
843 // Finished writing buffer_. Read some more, unless the request has been
844 // cancelled and deleted.
845 DCHECK_EQ(0, data
->BytesRemaining());
850 void URLFetcherCore::ReadResponse() {
851 // Some servers may treat HEAD requests as GET requests. To free up the
852 // network connection as soon as possible, signal that the request has
853 // completed immediately, without trying to read any data back (all we care
854 // about is the response code and headers, which we already have).
856 if (request_
->status().is_success() &&
857 (request_type_
!= URLFetcher::HEAD
)) {
858 if (!request_
->Read(buffer_
.get(), kBufferSize
, &bytes_read
))
859 bytes_read
= -1; // Match OnReadCompleted() interface contract.
861 OnReadCompleted(request_
.get(), bytes_read
);
864 void URLFetcherCore::InformDelegateUploadProgress() {
865 DCHECK(network_task_runner_
->BelongsToCurrentThread());
866 if (request_
.get()) {
867 int64 current
= request_
->GetUploadProgress().position();
868 if (current_upload_bytes_
!= current
) {
869 current_upload_bytes_
= current
;
871 if (!is_chunked_upload_
) {
872 total
= static_cast<int64
>(request_
->GetUploadProgress().size());
873 // Total may be zero if the UploadDataStream::Init has not been called
874 // yet. Don't send the upload progress until the size is initialized.
878 delegate_task_runner_
->PostTask(
881 &URLFetcherCore::InformDelegateUploadProgressInDelegateThread
,
882 this, current
, total
));
887 void URLFetcherCore::InformDelegateUploadProgressInDelegateThread(
888 int64 current
, int64 total
) {
889 DCHECK(delegate_task_runner_
->BelongsToCurrentThread());
891 delegate_
->OnURLFetchUploadProgress(fetcher_
, current
, total
);
894 void URLFetcherCore::InformDelegateDownloadProgress() {
895 DCHECK(network_task_runner_
->BelongsToCurrentThread());
897 // TODO(pkasting): Remove ScopedTracker below once crbug.com/455952 is fixed.
898 tracked_objects::ScopedTracker
tracking_profile2(
899 FROM_HERE_WITH_EXPLICIT_FUNCTION(
900 "455952 delegate_task_runner_->PostTask()"));
902 delegate_task_runner_
->PostTask(
905 &URLFetcherCore::InformDelegateDownloadProgressInDelegateThread
,
906 this, current_response_bytes_
, total_response_bytes_
));
909 void URLFetcherCore::InformDelegateDownloadProgressInDelegateThread(
910 int64 current
, int64 total
) {
911 DCHECK(delegate_task_runner_
->BelongsToCurrentThread());
913 delegate_
->OnURLFetchDownloadProgress(fetcher_
, current
, total
);
916 void URLFetcherCore::AssertHasNoUploadData() const {
917 DCHECK(!upload_content_set_
);
918 DCHECK(upload_content_
.empty());
919 DCHECK(upload_file_path_
.empty());
920 DCHECK(upload_stream_factory_
.is_null());