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_request.h"
8 #include "base/bind_helpers.h"
9 #include "base/callback.h"
10 #include "base/compiler_specific.h"
11 #include "base/debug/stack_trace.h"
12 #include "base/lazy_instance.h"
13 #include "base/memory/singleton.h"
14 #include "base/message_loop/message_loop.h"
15 #include "base/metrics/stats_counters.h"
16 #include "base/stl_util.h"
17 #include "base/strings/utf_string_conversions.h"
18 #include "base/synchronization/lock.h"
19 #include "base/values.h"
20 #include "net/base/auth.h"
21 #include "net/base/host_port_pair.h"
22 #include "net/base/load_flags.h"
23 #include "net/base/load_timing_info.h"
24 #include "net/base/net_errors.h"
25 #include "net/base/net_log.h"
26 #include "net/base/network_change_notifier.h"
27 #include "net/base/network_delegate.h"
28 #include "net/base/upload_data_stream.h"
29 #include "net/http/http_response_headers.h"
30 #include "net/http/http_util.h"
31 #include "net/ssl/ssl_cert_request_info.h"
32 #include "net/url_request/redirect_info.h"
33 #include "net/url_request/url_request_context.h"
34 #include "net/url_request/url_request_error_job.h"
35 #include "net/url_request/url_request_job.h"
36 #include "net/url_request/url_request_job_manager.h"
37 #include "net/url_request/url_request_netlog_params.h"
38 #include "net/url_request/url_request_redirect_job.h"
47 // Max number of http redirects to follow. Same number as gecko.
48 const int kMaxRedirects = 20;
50 // Discard headers which have meaning in POST (Content-Length, Content-Type,
52 void StripPostSpecificHeaders(HttpRequestHeaders* headers) {
53 // These are headers that may be attached to a POST.
54 headers->RemoveHeader(HttpRequestHeaders::kContentLength);
55 headers->RemoveHeader(HttpRequestHeaders::kContentType);
56 headers->RemoveHeader(HttpRequestHeaders::kOrigin);
59 // TODO(battre): Delete this, see http://crbug.com/89321:
60 // This counter keeps track of the identifiers used for URL requests so far.
61 // 0 is reserved to represent an invalid ID.
62 uint64 g_next_url_request_identifier = 1;
64 // This lock protects g_next_url_request_identifier.
65 base::LazyInstance<base::Lock>::Leaky
66 g_next_url_request_identifier_lock = LAZY_INSTANCE_INITIALIZER;
68 // Returns an prior unused identifier for URL requests.
69 uint64 GenerateURLRequestIdentifier() {
70 base::AutoLock lock(g_next_url_request_identifier_lock.Get());
71 return g_next_url_request_identifier++;
74 // True once the first URLRequest was started.
75 bool g_url_requests_started = false;
77 // True if cookies are accepted by default.
78 bool g_default_can_use_cookies = true;
80 // When the URLRequest first assempts load timing information, it has the times
81 // at which each event occurred. The API requires the time which the request
82 // was blocked on each phase. This function handles the conversion.
84 // In the case of reusing a SPDY session, old proxy results may have been
85 // reused, so proxy resolution times may be before the request was started.
87 // Due to preconnect and late binding, it is also possible for the connection
88 // attempt to start before a request has been started, or proxy resolution
91 // This functions fixes both those cases.
92 void ConvertRealLoadTimesToBlockingTimes(
93 net::LoadTimingInfo* load_timing_info) {
94 DCHECK(!load_timing_info->request_start.is_null());
96 // Earliest time possible for the request to be blocking on connect events.
97 base::TimeTicks block_on_connect = load_timing_info->request_start;
99 if (!load_timing_info->proxy_resolve_start.is_null()) {
100 DCHECK(!load_timing_info->proxy_resolve_end.is_null());
102 // Make sure the proxy times are after request start.
103 if (load_timing_info->proxy_resolve_start < load_timing_info->request_start)
104 load_timing_info->proxy_resolve_start = load_timing_info->request_start;
105 if (load_timing_info->proxy_resolve_end < load_timing_info->request_start)
106 load_timing_info->proxy_resolve_end = load_timing_info->request_start;
108 // Connect times must also be after the proxy times.
109 block_on_connect = load_timing_info->proxy_resolve_end;
112 // Make sure connection times are after start and proxy times.
114 net::LoadTimingInfo::ConnectTiming* connect_timing =
115 &load_timing_info->connect_timing;
116 if (!connect_timing->dns_start.is_null()) {
117 DCHECK(!connect_timing->dns_end.is_null());
118 if (connect_timing->dns_start < block_on_connect)
119 connect_timing->dns_start = block_on_connect;
120 if (connect_timing->dns_end < block_on_connect)
121 connect_timing->dns_end = block_on_connect;
124 if (!connect_timing->connect_start.is_null()) {
125 DCHECK(!connect_timing->connect_end.is_null());
126 if (connect_timing->connect_start < block_on_connect)
127 connect_timing->connect_start = block_on_connect;
128 if (connect_timing->connect_end < block_on_connect)
129 connect_timing->connect_end = block_on_connect;
132 if (!connect_timing->ssl_start.is_null()) {
133 DCHECK(!connect_timing->ssl_end.is_null());
134 if (connect_timing->ssl_start < block_on_connect)
135 connect_timing->ssl_start = block_on_connect;
136 if (connect_timing->ssl_end < block_on_connect)
137 connect_timing->ssl_end = block_on_connect;
143 void URLRequest::Deprecated::RegisterRequestInterceptor(
144 Interceptor* interceptor) {
145 URLRequest::RegisterRequestInterceptor(interceptor);
148 void URLRequest::Deprecated::UnregisterRequestInterceptor(
149 Interceptor* interceptor) {
150 URLRequest::UnregisterRequestInterceptor(interceptor);
153 ///////////////////////////////////////////////////////////////////////////////
154 // URLRequest::Interceptor
156 URLRequestJob* URLRequest::Interceptor::MaybeInterceptRedirect(
158 NetworkDelegate* network_delegate,
159 const GURL& location) {
163 URLRequestJob* URLRequest::Interceptor::MaybeInterceptResponse(
164 URLRequest* request, NetworkDelegate* network_delegate) {
168 ///////////////////////////////////////////////////////////////////////////////
169 // URLRequest::Delegate
171 void URLRequest::Delegate::OnReceivedRedirect(URLRequest* request,
172 const RedirectInfo& redirect_info,
173 bool* defer_redirect) {
176 void URLRequest::Delegate::OnAuthRequired(URLRequest* request,
177 AuthChallengeInfo* auth_info) {
178 request->CancelAuth();
181 void URLRequest::Delegate::OnCertificateRequested(
183 SSLCertRequestInfo* cert_request_info) {
187 void URLRequest::Delegate::OnSSLCertificateError(URLRequest* request,
188 const SSLInfo& ssl_info,
193 void URLRequest::Delegate::OnBeforeNetworkStart(URLRequest* request,
197 ///////////////////////////////////////////////////////////////////////////////
200 URLRequest::~URLRequest() {
203 if (network_delegate_) {
204 network_delegate_->NotifyURLRequestDestroyed(this);
206 job_->NotifyURLRequestDestroyed();
212 int deleted = context_->url_requests()->erase(this);
213 CHECK_EQ(1, deleted);
216 // Log error only on failure, not cancellation, as even successful requests
217 // are "cancelled" on destruction.
218 if (status_.status() == URLRequestStatus::FAILED)
219 net_error = status_.error();
220 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_REQUEST_ALIVE, net_error);
223 void URLRequest::EnableChunkedUpload() {
224 DCHECK(!upload_data_stream_ || upload_data_stream_->is_chunked());
225 if (!upload_data_stream_) {
226 upload_data_stream_.reset(
227 new UploadDataStream(UploadDataStream::CHUNKED, 0));
231 void URLRequest::AppendChunkToUpload(const char* bytes,
233 bool is_last_chunk) {
234 DCHECK(upload_data_stream_);
235 DCHECK(upload_data_stream_->is_chunked());
236 DCHECK_GT(bytes_len, 0);
237 upload_data_stream_->AppendChunk(bytes, bytes_len, is_last_chunk);
240 void URLRequest::set_upload(scoped_ptr<UploadDataStream> upload) {
241 DCHECK(!upload->is_chunked());
242 upload_data_stream_ = upload.Pass();
245 const UploadDataStream* URLRequest::get_upload() const {
246 return upload_data_stream_.get();
249 bool URLRequest::has_upload() const {
250 return upload_data_stream_.get() != NULL;
253 void URLRequest::SetExtraRequestHeaderById(int id, const string& value,
255 DCHECK(!is_pending_ || is_redirecting_);
256 NOTREACHED() << "implement me!";
259 void URLRequest::SetExtraRequestHeaderByName(const string& name,
262 DCHECK(!is_pending_ || is_redirecting_);
264 extra_request_headers_.SetHeader(name, value);
266 extra_request_headers_.SetHeaderIfMissing(name, value);
270 void URLRequest::RemoveRequestHeaderByName(const string& name) {
271 DCHECK(!is_pending_ || is_redirecting_);
272 extra_request_headers_.RemoveHeader(name);
275 void URLRequest::SetExtraRequestHeaders(
276 const HttpRequestHeaders& headers) {
277 DCHECK(!is_pending_);
278 extra_request_headers_ = headers;
280 // NOTE: This method will likely become non-trivial once the other setters
281 // for request headers are implemented.
284 bool URLRequest::GetFullRequestHeaders(HttpRequestHeaders* headers) const {
288 return job_->GetFullRequestHeaders(headers);
291 int64 URLRequest::GetTotalReceivedBytes() const {
295 return job_->GetTotalReceivedBytes();
298 LoadStateWithParam URLRequest::GetLoadState() const {
299 // The !blocked_by_.empty() check allows |this| to report it's blocked on a
300 // delegate before it has been started.
301 if (calling_delegate_ || !blocked_by_.empty()) {
302 return LoadStateWithParam(
303 LOAD_STATE_WAITING_FOR_DELEGATE,
304 use_blocked_by_as_load_param_ ? base::UTF8ToUTF16(blocked_by_) :
307 return LoadStateWithParam(job_.get() ? job_->GetLoadState() : LOAD_STATE_IDLE,
311 base::Value* URLRequest::GetStateAsValue() const {
312 base::DictionaryValue* dict = new base::DictionaryValue();
313 dict->SetString("url", original_url().possibly_invalid_spec());
315 if (url_chain_.size() > 1) {
316 base::ListValue* list = new base::ListValue();
317 for (std::vector<GURL>::const_iterator url = url_chain_.begin();
318 url != url_chain_.end(); ++url) {
319 list->AppendString(url->possibly_invalid_spec());
321 dict->Set("url_chain", list);
324 dict->SetInteger("load_flags", load_flags_);
326 LoadStateWithParam load_state = GetLoadState();
327 dict->SetInteger("load_state", load_state.state);
328 if (!load_state.param.empty())
329 dict->SetString("load_state_param", load_state.param);
330 if (!blocked_by_.empty())
331 dict->SetString("delegate_info", blocked_by_);
333 dict->SetString("method", method_);
334 dict->SetBoolean("has_upload", has_upload());
335 dict->SetBoolean("is_pending", is_pending_);
337 // Add the status of the request. The status should always be IO_PENDING, and
338 // the error should always be OK, unless something is holding onto a request
339 // that has finished or a request was leaked. Neither of these should happen.
340 switch (status_.status()) {
341 case URLRequestStatus::SUCCESS:
342 dict->SetString("status", "SUCCESS");
344 case URLRequestStatus::IO_PENDING:
345 dict->SetString("status", "IO_PENDING");
347 case URLRequestStatus::CANCELED:
348 dict->SetString("status", "CANCELED");
350 case URLRequestStatus::FAILED:
351 dict->SetString("status", "FAILED");
354 if (status_.error() != OK)
355 dict->SetInteger("net_error", status_.error());
359 void URLRequest::LogBlockedBy(const char* blocked_by) {
361 DCHECK_GT(strlen(blocked_by), 0u);
363 // Only log information to NetLog during startup and certain deferring calls
364 // to delegates. For all reads but the first, do nothing.
365 if (!calling_delegate_ && !response_info_.request_time.is_null())
369 blocked_by_ = blocked_by;
370 use_blocked_by_as_load_param_ = false;
373 NetLog::TYPE_DELEGATE_INFO,
374 NetLog::StringCallback("delegate_info", &blocked_by_));
377 void URLRequest::LogAndReportBlockedBy(const char* source) {
378 LogBlockedBy(source);
379 use_blocked_by_as_load_param_ = true;
382 void URLRequest::LogUnblocked() {
383 if (blocked_by_.empty())
386 net_log_.EndEvent(NetLog::TYPE_DELEGATE_INFO);
390 UploadProgress URLRequest::GetUploadProgress() const {
392 // We haven't started or the request was cancelled
393 return UploadProgress();
395 if (final_upload_progress_.position()) {
396 // The first job completed and none of the subsequent series of
397 // GETs when following redirects will upload anything, so we return the
398 // cached results from the initial job, the POST.
399 return final_upload_progress_;
401 return job_->GetUploadProgress();
404 void URLRequest::GetResponseHeaderById(int id, string* value) {
406 NOTREACHED() << "implement me!";
409 void URLRequest::GetResponseHeaderByName(const string& name, string* value) {
411 if (response_info_.headers.get()) {
412 response_info_.headers->GetNormalizedHeader(name, value);
418 void URLRequest::GetAllResponseHeaders(string* headers) {
420 if (response_info_.headers.get()) {
421 response_info_.headers->GetNormalizedHeaders(headers);
427 HostPortPair URLRequest::GetSocketAddress() const {
429 return job_->GetSocketAddress();
432 HttpResponseHeaders* URLRequest::response_headers() const {
433 return response_info_.headers.get();
436 void URLRequest::GetLoadTimingInfo(LoadTimingInfo* load_timing_info) const {
437 *load_timing_info = load_timing_info_;
440 bool URLRequest::GetResponseCookies(ResponseCookies* cookies) {
442 return job_->GetResponseCookies(cookies);
445 void URLRequest::GetMimeType(string* mime_type) const {
447 job_->GetMimeType(mime_type);
450 void URLRequest::GetCharset(string* charset) const {
452 job_->GetCharset(charset);
455 int URLRequest::GetResponseCode() const {
457 return job_->GetResponseCode();
460 void URLRequest::SetLoadFlags(int flags) {
461 if ((load_flags_ & LOAD_IGNORE_LIMITS) != (flags & LOAD_IGNORE_LIMITS)) {
463 DCHECK(flags & LOAD_IGNORE_LIMITS);
464 DCHECK_EQ(priority_, MAXIMUM_PRIORITY);
468 // This should be a no-op given the above DCHECKs, but do this
469 // anyway for release mode.
470 if ((load_flags_ & LOAD_IGNORE_LIMITS) != 0)
471 SetPriority(MAXIMUM_PRIORITY);
475 void URLRequest::SetDefaultCookiePolicyToBlock() {
476 CHECK(!g_url_requests_started);
477 g_default_can_use_cookies = false;
481 bool URLRequest::IsHandledProtocol(const std::string& scheme) {
482 return URLRequestJobManager::SupportsScheme(scheme);
486 bool URLRequest::IsHandledURL(const GURL& url) {
487 if (!url.is_valid()) {
488 // We handle error cases.
492 return IsHandledProtocol(url.scheme());
495 void URLRequest::set_first_party_for_cookies(
496 const GURL& first_party_for_cookies) {
497 DCHECK(!is_pending_);
498 first_party_for_cookies_ = first_party_for_cookies;
501 void URLRequest::set_first_party_url_policy(
502 FirstPartyURLPolicy first_party_url_policy) {
503 DCHECK(!is_pending_);
504 first_party_url_policy_ = first_party_url_policy;
507 void URLRequest::set_method(const std::string& method) {
508 DCHECK(!is_pending_);
513 std::string URLRequest::ComputeMethodForRedirect(
514 const std::string& method,
515 int http_status_code) {
516 // For 303 redirects, all request methods except HEAD are converted to GET,
517 // as per the latest httpbis draft. The draft also allows POST requests to
518 // be converted to GETs when following 301/302 redirects, for historical
519 // reasons. Most major browsers do this and so shall we. Both RFC 2616 and
520 // the httpbis draft say to prompt the user to confirm the generation of new
521 // requests, other than GET and HEAD requests, but IE omits these prompts and
523 // See: https://tools.ietf.org/html/draft-ietf-httpbis-p2-semantics-17#section-7.3
524 if ((http_status_code == 303 && method != "HEAD") ||
525 ((http_status_code == 301 || http_status_code == 302) &&
532 void URLRequest::SetReferrer(const std::string& referrer) {
533 DCHECK(!is_pending_);
534 GURL referrer_url(referrer);
535 if (referrer_url.is_valid()) {
536 referrer_ = referrer_url.GetAsReferrer().spec();
538 referrer_ = referrer;
542 void URLRequest::set_referrer_policy(ReferrerPolicy referrer_policy) {
543 DCHECK(!is_pending_);
544 referrer_policy_ = referrer_policy;
547 void URLRequest::set_delegate(Delegate* delegate) {
548 delegate_ = delegate;
551 void URLRequest::Start() {
552 // Some values can be NULL, but the job factory must not be.
553 DCHECK(context_->job_factory());
555 // Anything that sets |blocked_by_| before start should have cleaned up after
557 DCHECK(blocked_by_.empty());
559 g_url_requests_started = true;
560 response_info_.request_time = base::Time::Now();
562 load_timing_info_ = LoadTimingInfo();
563 load_timing_info_.request_start_time = response_info_.request_time;
564 load_timing_info_.request_start = base::TimeTicks::Now();
566 // Only notify the delegate for the initial request.
567 if (network_delegate_) {
569 int error = network_delegate_->NotifyBeforeURLRequest(
570 this, before_request_callback_, &delegate_redirect_url_);
571 // If ERR_IO_PENDING is returned, the delegate will invoke
572 // |before_request_callback_| later.
573 if (error != ERR_IO_PENDING)
574 BeforeRequestComplete(error);
578 StartJob(URLRequestJobManager::GetInstance()->CreateJob(
579 this, network_delegate_));
582 ///////////////////////////////////////////////////////////////////////////////
584 URLRequest::URLRequest(const GURL& url,
585 RequestPriority priority,
587 const URLRequestContext* context,
588 CookieStore* cookie_store,
589 NetworkDelegate* network_delegate)
591 network_delegate_(network_delegate ? network_delegate
592 : context->network_delegate()),
593 net_log_(BoundNetLog::Make(context->net_log(),
594 NetLog::SOURCE_URL_REQUEST)),
597 referrer_policy_(CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE),
598 first_party_url_policy_(NEVER_CHANGE_FIRST_PARTY_URL),
599 load_flags_(LOAD_NORMAL),
602 is_redirecting_(false),
603 redirect_limit_(kMaxRedirects),
605 identifier_(GenerateURLRequestIdentifier()),
606 calling_delegate_(false),
607 use_blocked_by_as_load_param_(false),
608 before_request_callback_(base::Bind(&URLRequest::BeforeRequestComplete,
609 base::Unretained(this))),
610 has_notified_completion_(false),
611 received_response_content_length_(0),
612 creation_time_(base::TimeTicks::Now()),
613 notified_before_network_start_(false),
614 cookie_store_(cookie_store ? cookie_store : context->cookie_store()) {
615 SIMPLE_STATS_COUNTER("URLRequestCount");
617 // Sanity check out environment.
618 DCHECK(base::MessageLoop::current())
619 << "The current base::MessageLoop must exist";
621 context->url_requests()->insert(this);
622 net_log_.BeginEvent(NetLog::TYPE_REQUEST_ALIVE);
626 void URLRequest::RegisterRequestInterceptor(Interceptor* interceptor) {
627 URLRequestJobManager::GetInstance()->RegisterRequestInterceptor(interceptor);
631 void URLRequest::UnregisterRequestInterceptor(Interceptor* interceptor) {
632 URLRequestJobManager::GetInstance()->UnregisterRequestInterceptor(
636 void URLRequest::BeforeRequestComplete(int error) {
638 DCHECK_NE(ERR_IO_PENDING, error);
640 // Check that there are no callbacks to already canceled requests.
641 DCHECK_NE(URLRequestStatus::CANCELED, status_.status());
643 OnCallToDelegateComplete();
646 std::string source("delegate");
647 net_log_.AddEvent(NetLog::TYPE_CANCELLED,
648 NetLog::StringCallback("source", &source));
649 StartJob(new URLRequestErrorJob(this, network_delegate_, error));
650 } else if (!delegate_redirect_url_.is_empty()) {
652 new_url.Swap(&delegate_redirect_url_);
654 URLRequestRedirectJob* job = new URLRequestRedirectJob(
655 this, network_delegate_, new_url,
656 // Use status code 307 to preserve the method, so POST requests work.
657 URLRequestRedirectJob::REDIRECT_307_TEMPORARY_REDIRECT, "Delegate");
660 StartJob(URLRequestJobManager::GetInstance()->CreateJob(
661 this, network_delegate_));
665 void URLRequest::StartJob(URLRequestJob* job) {
666 DCHECK(!is_pending_);
670 NetLog::TYPE_URL_REQUEST_START_JOB,
671 base::Bind(&NetLogURLRequestStartCallback,
672 &url(), &method_, load_flags_, priority_,
673 upload_data_stream_ ? upload_data_stream_->identifier() : -1));
676 job_->SetExtraRequestHeaders(extra_request_headers_);
677 job_->SetPriority(priority_);
679 if (upload_data_stream_.get())
680 job_->SetUpload(upload_data_stream_.get());
683 is_redirecting_ = false;
685 response_info_.was_cached = false;
687 // If the referrer is secure, but the requested URL is not, the referrer
688 // policy should be something non-default. If you hit this, please file a
690 if (referrer_policy_ ==
691 CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE &&
692 GURL(referrer_).SchemeIsSecure() && !url().SchemeIsSecure()) {
693 if (!network_delegate_ ||
694 !network_delegate_->CancelURLRequestWithPolicyViolatingReferrerHeader(
695 *this, url(), GURL(referrer_))) {
698 // We need to clear the referrer anyway to avoid an infinite recursion
699 // when starting the error job.
701 std::string source("delegate");
702 net_log_.AddEvent(NetLog::TYPE_CANCELLED,
703 NetLog::StringCallback("source", &source));
704 RestartWithJob(new URLRequestErrorJob(
705 this, network_delegate_, ERR_BLOCKED_BY_CLIENT));
710 // Don't allow errors to be sent from within Start().
711 // TODO(brettw) this may cause NotifyDone to be sent synchronously,
712 // we probably don't want this: they should be sent asynchronously so
713 // the caller does not get reentered.
717 void URLRequest::Restart() {
718 // Should only be called if the original job didn't make any progress.
719 DCHECK(job_.get() && !job_->has_response_started());
721 URLRequestJobManager::GetInstance()->CreateJob(this, network_delegate_));
724 void URLRequest::RestartWithJob(URLRequestJob *job) {
725 DCHECK(job->request() == this);
730 void URLRequest::Cancel() {
731 DoCancel(ERR_ABORTED, SSLInfo());
734 void URLRequest::CancelWithError(int error) {
735 DoCancel(error, SSLInfo());
738 void URLRequest::CancelWithSSLError(int error, const SSLInfo& ssl_info) {
739 // This should only be called on a started request.
740 if (!is_pending_ || !job_.get() || job_->has_response_started()) {
744 DoCancel(error, ssl_info);
747 void URLRequest::DoCancel(int error, const SSLInfo& ssl_info) {
749 // If cancelled while calling a delegate, clear delegate info.
750 if (calling_delegate_) {
752 OnCallToDelegateComplete();
755 // If the URL request already has an error status, then canceling is a no-op.
756 // Plus, we don't want to change the error status once it has been set.
757 if (status_.is_success()) {
758 status_.set_status(URLRequestStatus::CANCELED);
759 status_.set_error(error);
760 response_info_.ssl_info = ssl_info;
762 // If the request hasn't already been completed, log a cancellation event.
763 if (!has_notified_completion_) {
764 // Don't log an error code on ERR_ABORTED, since that's redundant.
765 net_log_.AddEventWithNetErrorCode(NetLog::TYPE_CANCELLED,
766 error == ERR_ABORTED ? OK : error);
770 if (is_pending_ && job_.get())
773 // We need to notify about the end of this job here synchronously. The
774 // Job sends an asynchronous notification but by the time this is processed,
775 // our |context_| is NULL.
776 NotifyRequestCompleted();
778 // The Job will call our NotifyDone method asynchronously. This is done so
779 // that the Delegate implementation can call Cancel without having to worry
780 // about being called recursively.
783 bool URLRequest::Read(IOBuffer* dest, int dest_size, int* bytes_read) {
788 // If this is the first read, end the delegate call that may have started in
789 // OnResponseStarted.
790 OnCallToDelegateComplete();
792 // This handles a cancel that happens while paused.
793 // TODO(ahendrickson): DCHECK() that it is not done after
794 // http://crbug.com/115705 is fixed.
798 if (dest_size == 0) {
799 // Caller is not too bright. I guess we've done what they asked.
803 // Once the request fails or is cancelled, read will just return 0 bytes
804 // to indicate end of stream.
805 if (!status_.is_success()) {
809 bool rv = job_->Read(dest, dest_size, bytes_read);
810 // If rv is false, the status cannot be success.
811 DCHECK(rv || status_.status() != URLRequestStatus::SUCCESS);
812 if (rv && *bytes_read <= 0 && status_.is_success())
813 NotifyRequestCompleted();
817 void URLRequest::StopCaching() {
822 void URLRequest::NotifyReceivedRedirect(const RedirectInfo& redirect_info,
823 bool* defer_redirect) {
824 is_redirecting_ = true;
826 // TODO(davidben): Pass the full RedirectInfo down to MaybeInterceptRedirect?
828 URLRequestJobManager::GetInstance()->MaybeInterceptRedirect(
829 this, network_delegate_, redirect_info.new_url);
832 } else if (delegate_) {
834 delegate_->OnReceivedRedirect(this, redirect_info, defer_redirect);
835 // |this| may be have been destroyed here.
839 void URLRequest::NotifyBeforeNetworkStart(bool* defer) {
840 if (delegate_ && !notified_before_network_start_) {
842 delegate_->OnBeforeNetworkStart(this, defer);
844 OnCallToDelegateComplete();
845 notified_before_network_start_ = true;
849 void URLRequest::ResumeNetworkStart() {
851 DCHECK(notified_before_network_start_);
853 OnCallToDelegateComplete();
854 job_->ResumeNetworkStart();
857 void URLRequest::NotifyResponseStarted() {
859 if (!status_.is_success())
860 net_error = status_.error();
861 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_URL_REQUEST_START_JOB,
865 URLRequestJobManager::GetInstance()->MaybeInterceptResponse(
866 this, network_delegate_);
871 // In some cases (e.g. an event was canceled), we might have sent the
872 // completion event and receive a NotifyResponseStarted() later.
873 if (!has_notified_completion_ && status_.is_success()) {
874 if (network_delegate_)
875 network_delegate_->NotifyResponseStarted(this);
878 // Notify in case the entire URL Request has been finished.
879 if (!has_notified_completion_ && !status_.is_success())
880 NotifyRequestCompleted();
883 delegate_->OnResponseStarted(this);
884 // Nothing may appear below this line as OnResponseStarted may delete
890 void URLRequest::FollowDeferredRedirect() {
892 CHECK(status_.is_success());
894 job_->FollowDeferredRedirect();
897 void URLRequest::SetAuth(const AuthCredentials& credentials) {
899 DCHECK(job_->NeedsAuth());
901 job_->SetAuth(credentials);
904 void URLRequest::CancelAuth() {
906 DCHECK(job_->NeedsAuth());
911 void URLRequest::ContinueWithCertificate(X509Certificate* client_cert) {
914 job_->ContinueWithCertificate(client_cert);
917 void URLRequest::ContinueDespiteLastError() {
920 job_->ContinueDespiteLastError();
923 void URLRequest::PrepareToRestart() {
926 // Close the current URL_REQUEST_START_JOB, since we will be starting a new
928 net_log_.EndEvent(NetLog::TYPE_URL_REQUEST_START_JOB);
932 response_info_ = HttpResponseInfo();
933 response_info_.request_time = base::Time::Now();
935 load_timing_info_ = LoadTimingInfo();
936 load_timing_info_.request_start_time = response_info_.request_time;
937 load_timing_info_.request_start = base::TimeTicks::Now();
939 status_ = URLRequestStatus();
943 void URLRequest::OrphanJob() {
944 // When calling this function, please check that URLRequestHttpJob is
945 // not in between calling NetworkDelegate::NotifyHeadersReceived receiving
946 // the call back. This is currently guaranteed by the following strategies:
947 // - OrphanJob is called on JobRestart, in this case the URLRequestJob cannot
948 // be receiving any headers at that time.
949 // - OrphanJob is called in ~URLRequest, in this case
950 // NetworkDelegate::NotifyURLRequestDestroyed notifies the NetworkDelegate
951 // that the callback becomes invalid.
953 job_->DetachRequest(); // ensures that the job will not call us again
957 int URLRequest::Redirect(const RedirectInfo& redirect_info) {
958 // Matches call in NotifyReceivedRedirect.
959 OnCallToDelegateComplete();
960 if (net_log_.IsLogging()) {
962 NetLog::TYPE_URL_REQUEST_REDIRECTED,
963 NetLog::StringCallback("location",
964 &redirect_info.new_url.possibly_invalid_spec()));
967 // TODO(davidben): Pass the full RedirectInfo to the NetworkDelegate.
968 if (network_delegate_)
969 network_delegate_->NotifyBeforeRedirect(this, redirect_info.new_url);
971 if (redirect_limit_ <= 0) {
972 DVLOG(1) << "disallowing redirect: exceeds limit";
973 return ERR_TOO_MANY_REDIRECTS;
976 if (!redirect_info.new_url.is_valid())
977 return ERR_INVALID_URL;
979 if (!job_->IsSafeRedirect(redirect_info.new_url)) {
980 DVLOG(1) << "disallowing redirect: unsafe protocol";
981 return ERR_UNSAFE_REDIRECT;
984 if (!final_upload_progress_.position())
985 final_upload_progress_ = job_->GetUploadProgress();
988 if (redirect_info.new_method != method_) {
989 // TODO(davidben): This logic still needs to be replicated at the consumers.
990 if (method_ == "POST") {
991 // If being switched from POST, must remove headers that were specific to
992 // the POST and don't have meaning in other methods. For example the
993 // inclusion of a multipart Content-Type header in GET can cause problems
994 // with some servers:
995 // http://code.google.com/p/chromium/issues/detail?id=843
996 StripPostSpecificHeaders(&extra_request_headers_);
998 upload_data_stream_.reset();
999 method_ = redirect_info.new_method;
1002 referrer_ = redirect_info.new_referrer;
1003 first_party_for_cookies_ = redirect_info.new_first_party_for_cookies;
1005 url_chain_.push_back(redirect_info.new_url);
1012 const URLRequestContext* URLRequest::context() const {
1016 int64 URLRequest::GetExpectedContentSize() const {
1017 int64 expected_content_size = -1;
1019 expected_content_size = job_->expected_content_size();
1021 return expected_content_size;
1024 void URLRequest::SetPriority(RequestPriority priority) {
1025 DCHECK_GE(priority, MINIMUM_PRIORITY);
1026 DCHECK_LE(priority, MAXIMUM_PRIORITY);
1028 if ((load_flags_ & LOAD_IGNORE_LIMITS) && (priority != MAXIMUM_PRIORITY)) {
1030 // Maintain the invariant that requests with IGNORE_LIMITS set
1031 // have MAXIMUM_PRIORITY for release mode.
1035 if (priority_ == priority)
1038 priority_ = priority;
1040 net_log_.AddEvent(NetLog::TYPE_URL_REQUEST_SET_PRIORITY,
1041 NetLog::IntegerCallback("priority", priority_));
1042 job_->SetPriority(priority_);
1046 bool URLRequest::GetHSTSRedirect(GURL* redirect_url) const {
1047 const GURL& url = this->url();
1048 if (!url.SchemeIs("http"))
1050 TransportSecurityState* state = context()->transport_security_state();
1051 if (state && state->ShouldUpgradeToSSL(url.host())) {
1052 url::Replacements<char> replacements;
1053 const char kNewScheme[] = "https";
1054 replacements.SetScheme(kNewScheme, url::Component(0, strlen(kNewScheme)));
1055 *redirect_url = url.ReplaceComponents(replacements);
1061 void URLRequest::NotifyAuthRequired(AuthChallengeInfo* auth_info) {
1062 NetworkDelegate::AuthRequiredResponse rv =
1063 NetworkDelegate::AUTH_REQUIRED_RESPONSE_NO_ACTION;
1064 auth_info_ = auth_info;
1065 if (network_delegate_) {
1067 rv = network_delegate_->NotifyAuthRequired(
1070 base::Bind(&URLRequest::NotifyAuthRequiredComplete,
1071 base::Unretained(this)),
1072 &auth_credentials_);
1073 if (rv == NetworkDelegate::AUTH_REQUIRED_RESPONSE_IO_PENDING)
1077 NotifyAuthRequiredComplete(rv);
1080 void URLRequest::NotifyAuthRequiredComplete(
1081 NetworkDelegate::AuthRequiredResponse result) {
1082 OnCallToDelegateComplete();
1084 // Check that there are no callbacks to already canceled requests.
1085 DCHECK_NE(URLRequestStatus::CANCELED, status_.status());
1087 // NotifyAuthRequired may be called multiple times, such as
1088 // when an authentication attempt fails. Clear out the data
1089 // so it can be reset on another round.
1090 AuthCredentials credentials = auth_credentials_;
1091 auth_credentials_ = AuthCredentials();
1092 scoped_refptr<AuthChallengeInfo> auth_info;
1093 auth_info.swap(auth_info_);
1096 case NetworkDelegate::AUTH_REQUIRED_RESPONSE_NO_ACTION:
1097 // Defer to the URLRequest::Delegate, since the NetworkDelegate
1098 // didn't take an action.
1100 delegate_->OnAuthRequired(this, auth_info.get());
1103 case NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH:
1104 SetAuth(credentials);
1107 case NetworkDelegate::AUTH_REQUIRED_RESPONSE_CANCEL_AUTH:
1111 case NetworkDelegate::AUTH_REQUIRED_RESPONSE_IO_PENDING:
1117 void URLRequest::NotifyCertificateRequested(
1118 SSLCertRequestInfo* cert_request_info) {
1120 delegate_->OnCertificateRequested(this, cert_request_info);
1123 void URLRequest::NotifySSLCertificateError(const SSLInfo& ssl_info,
1126 delegate_->OnSSLCertificateError(this, ssl_info, fatal);
1129 bool URLRequest::CanGetCookies(const CookieList& cookie_list) const {
1130 DCHECK(!(load_flags_ & LOAD_DO_NOT_SEND_COOKIES));
1131 if (network_delegate_) {
1132 return network_delegate_->CanGetCookies(*this, cookie_list);
1134 return g_default_can_use_cookies;
1137 bool URLRequest::CanSetCookie(const std::string& cookie_line,
1138 CookieOptions* options) const {
1139 DCHECK(!(load_flags_ & LOAD_DO_NOT_SAVE_COOKIES));
1140 if (network_delegate_) {
1141 return network_delegate_->CanSetCookie(*this, cookie_line, options);
1143 return g_default_can_use_cookies;
1146 bool URLRequest::CanEnablePrivacyMode() const {
1147 if (network_delegate_) {
1148 return network_delegate_->CanEnablePrivacyMode(url(),
1149 first_party_for_cookies_);
1151 return !g_default_can_use_cookies;
1155 void URLRequest::NotifyReadCompleted(int bytes_read) {
1156 // Notify in case the entire URL Request has been finished.
1157 if (bytes_read <= 0)
1158 NotifyRequestCompleted();
1160 // Notify NetworkChangeNotifier that we just received network data.
1161 // This is to identify cases where the NetworkChangeNotifier thinks we
1162 // are off-line but we are still receiving network data (crbug.com/124069),
1163 // and to get rough network connection measurements.
1164 if (bytes_read > 0 && !was_cached())
1165 NetworkChangeNotifier::NotifyDataReceived(*this, bytes_read);
1168 delegate_->OnReadCompleted(this, bytes_read);
1170 // Nothing below this line as OnReadCompleted may delete |this|.
1173 void URLRequest::OnHeadersComplete() {
1174 // Cache load timing information now, as information will be lost once the
1175 // socket is closed and the ClientSocketHandle is Reset, which will happen
1176 // once the body is complete. The start times should already be populated.
1178 // Keep a copy of the two times the URLRequest sets.
1179 base::TimeTicks request_start = load_timing_info_.request_start;
1180 base::Time request_start_time = load_timing_info_.request_start_time;
1182 // Clear load times. Shouldn't be neded, but gives the GetLoadTimingInfo a
1183 // consistent place to start from.
1184 load_timing_info_ = LoadTimingInfo();
1185 job_->GetLoadTimingInfo(&load_timing_info_);
1187 load_timing_info_.request_start = request_start;
1188 load_timing_info_.request_start_time = request_start_time;
1190 ConvertRealLoadTimesToBlockingTimes(&load_timing_info_);
1194 void URLRequest::NotifyRequestCompleted() {
1195 // TODO(battre): Get rid of this check, according to willchan it should
1197 if (has_notified_completion_)
1200 is_pending_ = false;
1201 is_redirecting_ = false;
1202 has_notified_completion_ = true;
1203 if (network_delegate_)
1204 network_delegate_->NotifyCompleted(this, job_.get() != NULL);
1207 void URLRequest::OnCallToDelegate() {
1208 DCHECK(!calling_delegate_);
1209 DCHECK(blocked_by_.empty());
1210 calling_delegate_ = true;
1211 net_log_.BeginEvent(NetLog::TYPE_URL_REQUEST_DELEGATE);
1214 void URLRequest::OnCallToDelegateComplete() {
1215 // This should have been cleared before resuming the request.
1216 DCHECK(blocked_by_.empty());
1217 if (!calling_delegate_)
1219 calling_delegate_ = false;
1220 net_log_.EndEvent(NetLog::TYPE_URL_REQUEST_DELEGATE);
1223 void URLRequest::set_stack_trace(const base::debug::StackTrace& stack_trace) {
1224 base::debug::StackTrace* stack_trace_copy =
1225 new base::debug::StackTrace(NULL, 0);
1226 *stack_trace_copy = stack_trace;
1227 stack_trace_.reset(stack_trace_copy);
1230 const base::debug::StackTrace* URLRequest::stack_trace() const {
1231 return stack_trace_.get();