• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2012 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #include "net/url_request/url_request.h"
6 
7 #include <utility>
8 
9 #include "base/compiler_specific.h"
10 #include "base/functional/bind.h"
11 #include "base/functional/callback.h"
12 #include "base/functional/callback_helpers.h"
13 #include "base/metrics/histogram_macros.h"
14 #include "base/rand_util.h"
15 #include "base/strings/utf_string_conversions.h"
16 #include "base/synchronization/lock.h"
17 #include "base/task/single_thread_task_runner.h"
18 #include "base/types/pass_key.h"
19 #include "base/values.h"
20 #include "net/base/auth.h"
21 #include "net/base/io_buffer.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/network_change_notifier.h"
26 #include "net/base/network_delegate.h"
27 #include "net/base/upload_data_stream.h"
28 #include "net/cert/x509_certificate.h"
29 #include "net/cookies/cookie_store.h"
30 #include "net/cookies/cookie_util.h"
31 #include "net/dns/public/secure_dns_policy.h"
32 #include "net/http/http_log_util.h"
33 #include "net/http/http_util.h"
34 #include "net/log/net_log.h"
35 #include "net/log/net_log_event_type.h"
36 #include "net/log/net_log_source_type.h"
37 #include "net/socket/next_proto.h"
38 #include "net/ssl/ssl_cert_request_info.h"
39 #include "net/ssl/ssl_private_key.h"
40 #include "net/url_request/redirect_info.h"
41 #include "net/url_request/redirect_util.h"
42 #include "net/url_request/url_request_context.h"
43 #include "net/url_request/url_request_error_job.h"
44 #include "net/url_request/url_request_job.h"
45 #include "net/url_request/url_request_job_factory.h"
46 #include "net/url_request/url_request_netlog_params.h"
47 #include "net/url_request/url_request_redirect_job.h"
48 #include "url/gurl.h"
49 #include "url/origin.h"
50 
51 namespace net {
52 
53 namespace {
54 
55 // True once the first URLRequest was started.
56 bool g_url_requests_started = false;
57 
58 // True if cookies are accepted by default.
59 bool g_default_can_use_cookies = true;
60 
61 // When the URLRequest first assempts load timing information, it has the times
62 // at which each event occurred.  The API requires the time which the request
63 // was blocked on each phase.  This function handles the conversion.
64 //
65 // In the case of reusing a SPDY session, old proxy results may have been
66 // reused, so proxy resolution times may be before the request was started.
67 //
68 // Due to preconnect and late binding, it is also possible for the connection
69 // attempt to start before a request has been started, or proxy resolution
70 // completed.
71 //
72 // This functions fixes both those cases.
ConvertRealLoadTimesToBlockingTimes(LoadTimingInfo * load_timing_info)73 void ConvertRealLoadTimesToBlockingTimes(LoadTimingInfo* load_timing_info) {
74   DCHECK(!load_timing_info->request_start.is_null());
75 
76   // Earliest time possible for the request to be blocking on connect events.
77   base::TimeTicks block_on_connect = load_timing_info->request_start;
78 
79   if (!load_timing_info->proxy_resolve_start.is_null()) {
80     DCHECK(!load_timing_info->proxy_resolve_end.is_null());
81 
82     // Make sure the proxy times are after request start.
83     if (load_timing_info->proxy_resolve_start < load_timing_info->request_start)
84       load_timing_info->proxy_resolve_start = load_timing_info->request_start;
85     if (load_timing_info->proxy_resolve_end < load_timing_info->request_start)
86       load_timing_info->proxy_resolve_end = load_timing_info->request_start;
87 
88     // Connect times must also be after the proxy times.
89     block_on_connect = load_timing_info->proxy_resolve_end;
90   }
91 
92   if (!load_timing_info->receive_headers_start.is_null() &&
93       load_timing_info->receive_headers_start < block_on_connect) {
94     load_timing_info->receive_headers_start = block_on_connect;
95   }
96   if (!load_timing_info->receive_non_informational_headers_start.is_null() &&
97       load_timing_info->receive_non_informational_headers_start <
98           block_on_connect) {
99     load_timing_info->receive_non_informational_headers_start =
100         block_on_connect;
101   }
102 
103   // Make sure connection times are after start and proxy times.
104 
105   LoadTimingInfo::ConnectTiming* connect_timing =
106       &load_timing_info->connect_timing;
107   if (!connect_timing->domain_lookup_start.is_null()) {
108     DCHECK(!connect_timing->domain_lookup_end.is_null());
109     if (connect_timing->domain_lookup_start < block_on_connect)
110       connect_timing->domain_lookup_start = block_on_connect;
111     if (connect_timing->domain_lookup_end < block_on_connect)
112       connect_timing->domain_lookup_end = block_on_connect;
113   }
114 
115   if (!connect_timing->connect_start.is_null()) {
116     DCHECK(!connect_timing->connect_end.is_null());
117     if (connect_timing->connect_start < block_on_connect)
118       connect_timing->connect_start = block_on_connect;
119     if (connect_timing->connect_end < block_on_connect)
120       connect_timing->connect_end = block_on_connect;
121   }
122 
123   if (!connect_timing->ssl_start.is_null()) {
124     DCHECK(!connect_timing->ssl_end.is_null());
125     if (connect_timing->ssl_start < block_on_connect)
126       connect_timing->ssl_start = block_on_connect;
127     if (connect_timing->ssl_end < block_on_connect)
128       connect_timing->ssl_end = block_on_connect;
129   }
130 }
131 
CreateNetLogWithSource(NetLog * net_log,absl::optional<net::NetLogSource> net_log_source)132 NetLogWithSource CreateNetLogWithSource(
133     NetLog* net_log,
134     absl::optional<net::NetLogSource> net_log_source) {
135   if (net_log_source) {
136     return NetLogWithSource::Make(net_log, net_log_source.value());
137   }
138   return NetLogWithSource::Make(net_log, NetLogSourceType::URL_REQUEST);
139 }
140 
141 }  // namespace
142 
143 ///////////////////////////////////////////////////////////////////////////////
144 // URLRequest::Delegate
145 
OnConnected(URLRequest * request,const TransportInfo & info,CompletionOnceCallback callback)146 int URLRequest::Delegate::OnConnected(URLRequest* request,
147                                       const TransportInfo& info,
148                                       CompletionOnceCallback callback) {
149   return OK;
150 }
151 
OnReceivedRedirect(URLRequest * request,const RedirectInfo & redirect_info,bool * defer_redirect)152 void URLRequest::Delegate::OnReceivedRedirect(URLRequest* request,
153                                               const RedirectInfo& redirect_info,
154                                               bool* defer_redirect) {}
155 
OnAuthRequired(URLRequest * request,const AuthChallengeInfo & auth_info)156 void URLRequest::Delegate::OnAuthRequired(URLRequest* request,
157                                           const AuthChallengeInfo& auth_info) {
158   request->CancelAuth();
159 }
160 
OnCertificateRequested(URLRequest * request,SSLCertRequestInfo * cert_request_info)161 void URLRequest::Delegate::OnCertificateRequested(
162     URLRequest* request,
163     SSLCertRequestInfo* cert_request_info) {
164   request->CancelWithError(ERR_SSL_CLIENT_AUTH_CERT_NEEDED);
165 }
166 
OnSSLCertificateError(URLRequest * request,int net_error,const SSLInfo & ssl_info,bool is_hsts_ok)167 void URLRequest::Delegate::OnSSLCertificateError(URLRequest* request,
168                                                  int net_error,
169                                                  const SSLInfo& ssl_info,
170                                                  bool is_hsts_ok) {
171   request->Cancel();
172 }
173 
OnResponseStarted(URLRequest * request,int net_error)174 void URLRequest::Delegate::OnResponseStarted(URLRequest* request,
175                                              int net_error) {
176   NOTREACHED();
177 }
178 
179 ///////////////////////////////////////////////////////////////////////////////
180 // URLRequest
181 
~URLRequest()182 URLRequest::~URLRequest() {
183   DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
184 
185   // Log the redirect count during destruction, to ensure that it is only
186   // recorded at the end of following all redirect chains.
187   UMA_HISTOGRAM_EXACT_LINEAR("Net.RedirectChainLength",
188                              kMaxRedirects - redirect_limit_,
189                              kMaxRedirects + 1);
190 
191   Cancel();
192 
193   if (network_delegate()) {
194     network_delegate()->NotifyURLRequestDestroyed(this);
195     if (job_.get())
196       job_->NotifyURLRequestDestroyed();
197   }
198 
199   // Delete job before |this|, since subclasses may do weird things, like depend
200   // on UserData associated with |this| and poke at it during teardown.
201   job_.reset();
202 
203   DCHECK_EQ(1u, context_->url_requests()->count(this));
204   context_->url_requests()->erase(this);
205 
206   int net_error = OK;
207   // Log error only on failure, not cancellation, as even successful requests
208   // are "cancelled" on destruction.
209   if (status_ != ERR_ABORTED)
210     net_error = status_;
211   net_log_.EndEventWithNetErrorCode(NetLogEventType::REQUEST_ALIVE, net_error);
212 }
213 
set_upload(std::unique_ptr<UploadDataStream> upload)214 void URLRequest::set_upload(std::unique_ptr<UploadDataStream> upload) {
215   upload_data_stream_ = std::move(upload);
216 }
217 
get_upload_for_testing() const218 const UploadDataStream* URLRequest::get_upload_for_testing() const {
219   return upload_data_stream_.get();
220 }
221 
has_upload() const222 bool URLRequest::has_upload() const {
223   return upload_data_stream_.get() != nullptr;
224 }
225 
SetExtraRequestHeaderByName(base::StringPiece name,base::StringPiece value,bool overwrite)226 void URLRequest::SetExtraRequestHeaderByName(base::StringPiece name,
227                                              base::StringPiece value,
228                                              bool overwrite) {
229   DCHECK(!is_pending_ || is_redirecting_);
230   if (overwrite) {
231     extra_request_headers_.SetHeader(name, value);
232   } else {
233     extra_request_headers_.SetHeaderIfMissing(name, value);
234   }
235 }
236 
RemoveRequestHeaderByName(base::StringPiece name)237 void URLRequest::RemoveRequestHeaderByName(base::StringPiece name) {
238   DCHECK(!is_pending_ || is_redirecting_);
239   extra_request_headers_.RemoveHeader(name);
240 }
241 
SetExtraRequestHeaders(const HttpRequestHeaders & headers)242 void URLRequest::SetExtraRequestHeaders(const HttpRequestHeaders& headers) {
243   DCHECK(!is_pending_);
244   extra_request_headers_ = headers;
245 
246   // NOTE: This method will likely become non-trivial once the other setters
247   // for request headers are implemented.
248 }
249 
GetTotalReceivedBytes() const250 int64_t URLRequest::GetTotalReceivedBytes() const {
251   if (!job_.get())
252     return 0;
253 
254   return job_->GetTotalReceivedBytes();
255 }
256 
GetTotalSentBytes() const257 int64_t URLRequest::GetTotalSentBytes() const {
258   if (!job_.get())
259     return 0;
260 
261   return job_->GetTotalSentBytes();
262 }
263 
GetRawBodyBytes() const264 int64_t URLRequest::GetRawBodyBytes() const {
265   if (!job_.get())
266     return 0;
267 
268   return job_->prefilter_bytes_read();
269 }
270 
GetLoadState() const271 LoadStateWithParam URLRequest::GetLoadState() const {
272   // The !blocked_by_.empty() check allows |this| to report it's blocked on a
273   // delegate before it has been started.
274   if (calling_delegate_ || !blocked_by_.empty()) {
275     return LoadStateWithParam(LOAD_STATE_WAITING_FOR_DELEGATE,
276                               use_blocked_by_as_load_param_
277                                   ? base::UTF8ToUTF16(blocked_by_)
278                                   : std::u16string());
279   }
280   return LoadStateWithParam(job_.get() ? job_->GetLoadState() : LOAD_STATE_IDLE,
281                             std::u16string());
282 }
283 
GetStateAsValue() const284 base::Value::Dict URLRequest::GetStateAsValue() const {
285   base::Value::Dict dict;
286   dict.Set("url", original_url().possibly_invalid_spec());
287 
288   if (url_chain_.size() > 1) {
289     base::Value::List list;
290     for (const GURL& url : url_chain_) {
291       list.Append(url.possibly_invalid_spec());
292     }
293     dict.Set("url_chain", std::move(list));
294   }
295 
296   dict.Set("load_flags", load_flags_);
297 
298   LoadStateWithParam load_state = GetLoadState();
299   dict.Set("load_state", load_state.state);
300   if (!load_state.param.empty())
301     dict.Set("load_state_param", load_state.param);
302   if (!blocked_by_.empty())
303     dict.Set("delegate_blocked_by", blocked_by_);
304 
305   dict.Set("method", method_);
306   // TODO(https://crbug.com/1343856): Update "network_isolation_key" to
307   // "network_anonymization_key" and change NetLog viewer.
308   dict.Set("network_isolation_key",
309            isolation_info_.network_isolation_key().ToDebugString());
310   dict.Set("has_upload", has_upload());
311   dict.Set("is_pending", is_pending_);
312 
313   dict.Set("traffic_annotation", traffic_annotation_.unique_id_hash_code);
314 
315   if (status_ != OK)
316     dict.Set("net_error", status_);
317   return dict;
318 }
319 
LogBlockedBy(base::StringPiece blocked_by)320 void URLRequest::LogBlockedBy(base::StringPiece blocked_by) {
321   DCHECK(!blocked_by.empty());
322 
323   // Only log information to NetLog during startup and certain deferring calls
324   // to delegates.  For all reads but the first, do nothing.
325   if (!calling_delegate_ && !response_info_.request_time.is_null())
326     return;
327 
328   LogUnblocked();
329   blocked_by_ = std::string(blocked_by);
330   use_blocked_by_as_load_param_ = false;
331 
332   net_log_.BeginEventWithStringParams(NetLogEventType::DELEGATE_INFO,
333                                       "delegate_blocked_by", blocked_by_);
334 }
335 
LogAndReportBlockedBy(base::StringPiece source)336 void URLRequest::LogAndReportBlockedBy(base::StringPiece source) {
337   LogBlockedBy(source);
338   use_blocked_by_as_load_param_ = true;
339 }
340 
LogUnblocked()341 void URLRequest::LogUnblocked() {
342   if (blocked_by_.empty())
343     return;
344 
345   net_log_.EndEvent(NetLogEventType::DELEGATE_INFO);
346   blocked_by_.clear();
347 }
348 
GetUploadProgress() const349 UploadProgress URLRequest::GetUploadProgress() const {
350   if (!job_.get()) {
351     // We haven't started or the request was cancelled
352     return UploadProgress();
353   }
354 
355   if (final_upload_progress_.position()) {
356     // The first job completed and none of the subsequent series of
357     // GETs when following redirects will upload anything, so we return the
358     // cached results from the initial job, the POST.
359     return final_upload_progress_;
360   }
361 
362   if (upload_data_stream_)
363     return upload_data_stream_->GetUploadProgress();
364 
365   return UploadProgress();
366 }
367 
GetResponseHeaderByName(base::StringPiece name,std::string * value) const368 void URLRequest::GetResponseHeaderByName(base::StringPiece name,
369                                          std::string* value) const {
370   DCHECK(value);
371   if (response_info_.headers.get()) {
372     response_info_.headers->GetNormalizedHeader(name, value);
373   } else {
374     value->clear();
375   }
376 }
377 
GetResponseRemoteEndpoint() const378 IPEndPoint URLRequest::GetResponseRemoteEndpoint() const {
379   DCHECK(job_.get());
380   return job_->GetResponseRemoteEndpoint();
381 }
382 
response_headers() const383 HttpResponseHeaders* URLRequest::response_headers() const {
384   return response_info_.headers.get();
385 }
386 
auth_challenge_info() const387 const absl::optional<AuthChallengeInfo>& URLRequest::auth_challenge_info()
388     const {
389   return response_info_.auth_challenge;
390 }
391 
GetLoadTimingInfo(LoadTimingInfo * load_timing_info) const392 void URLRequest::GetLoadTimingInfo(LoadTimingInfo* load_timing_info) const {
393   *load_timing_info = load_timing_info_;
394 }
395 
PopulateNetErrorDetails(NetErrorDetails * details) const396 void URLRequest::PopulateNetErrorDetails(NetErrorDetails* details) const {
397   if (!job_)
398     return;
399   return job_->PopulateNetErrorDetails(details);
400 }
401 
GetTransactionRemoteEndpoint(IPEndPoint * endpoint) const402 bool URLRequest::GetTransactionRemoteEndpoint(IPEndPoint* endpoint) const {
403   if (!job_)
404     return false;
405 
406   return job_->GetTransactionRemoteEndpoint(endpoint);
407 }
408 
GetMimeType(std::string * mime_type) const409 void URLRequest::GetMimeType(std::string* mime_type) const {
410   DCHECK(job_.get());
411   job_->GetMimeType(mime_type);
412 }
413 
GetCharset(std::string * charset) const414 void URLRequest::GetCharset(std::string* charset) const {
415   DCHECK(job_.get());
416   job_->GetCharset(charset);
417 }
418 
GetResponseCode() const419 int URLRequest::GetResponseCode() const {
420   DCHECK(job_.get());
421   return job_->GetResponseCode();
422 }
423 
set_maybe_sent_cookies(CookieAccessResultList cookies)424 void URLRequest::set_maybe_sent_cookies(CookieAccessResultList cookies) {
425   maybe_sent_cookies_ = std::move(cookies);
426 }
427 
set_maybe_stored_cookies(CookieAndLineAccessResultList cookies)428 void URLRequest::set_maybe_stored_cookies(
429     CookieAndLineAccessResultList cookies) {
430   maybe_stored_cookies_ = std::move(cookies);
431 }
432 
SetLoadFlags(int flags)433 void URLRequest::SetLoadFlags(int flags) {
434   if ((load_flags_ & LOAD_IGNORE_LIMITS) != (flags & LOAD_IGNORE_LIMITS)) {
435     DCHECK(!job_.get());
436     DCHECK(flags & LOAD_IGNORE_LIMITS);
437     DCHECK_EQ(priority_, MAXIMUM_PRIORITY);
438   }
439   load_flags_ = flags;
440 
441   // This should be a no-op given the above DCHECKs, but do this
442   // anyway for release mode.
443   if ((load_flags_ & LOAD_IGNORE_LIMITS) != 0)
444     SetPriority(MAXIMUM_PRIORITY);
445 }
446 
SetSecureDnsPolicy(SecureDnsPolicy secure_dns_policy)447 void URLRequest::SetSecureDnsPolicy(SecureDnsPolicy secure_dns_policy) {
448   secure_dns_policy_ = secure_dns_policy;
449 }
450 
451 // static
SetDefaultCookiePolicyToBlock()452 void URLRequest::SetDefaultCookiePolicyToBlock() {
453   CHECK(!g_url_requests_started);
454   g_default_can_use_cookies = false;
455 }
456 
SetURLChain(const std::vector<GURL> & url_chain)457 void URLRequest::SetURLChain(const std::vector<GURL>& url_chain) {
458   DCHECK(!job_);
459   DCHECK(!is_pending_);
460   DCHECK_EQ(url_chain_.size(), 1u);
461 
462   if (url_chain.size() < 2)
463     return;
464 
465   // In most cases the current request URL will match the last URL in the
466   // explicitly set URL chain.  In some cases, however, a throttle will modify
467   // the request URL resulting in a different request URL.  We handle this by
468   // using previous values from the explicitly set URL chain, but with the
469   // request URL as the final entry in the chain.
470   url_chain_.insert(url_chain_.begin(), url_chain.begin(),
471                     url_chain.begin() + url_chain.size() - 1);
472 }
473 
set_site_for_cookies(const SiteForCookies & site_for_cookies)474 void URLRequest::set_site_for_cookies(const SiteForCookies& site_for_cookies) {
475   DCHECK(!is_pending_);
476   site_for_cookies_ = site_for_cookies;
477 }
478 
set_isolation_info_from_network_anonymization_key(const NetworkAnonymizationKey & network_anonymization_key)479 void URLRequest::set_isolation_info_from_network_anonymization_key(
480     const NetworkAnonymizationKey& network_anonymization_key) {
481   set_isolation_info(URLRequest::CreateIsolationInfoFromNetworkAnonymizationKey(
482       network_anonymization_key));
483 
484   is_created_from_network_anonymization_key_ = true;
485 }
486 
set_first_party_url_policy(RedirectInfo::FirstPartyURLPolicy first_party_url_policy)487 void URLRequest::set_first_party_url_policy(
488     RedirectInfo::FirstPartyURLPolicy first_party_url_policy) {
489   DCHECK(!is_pending_);
490   first_party_url_policy_ = first_party_url_policy;
491 }
492 
set_initiator(const absl::optional<url::Origin> & initiator)493 void URLRequest::set_initiator(const absl::optional<url::Origin>& initiator) {
494   DCHECK(!is_pending_);
495   DCHECK(!initiator.has_value() || initiator.value().opaque() ||
496          initiator.value().GetURL().is_valid());
497   initiator_ = initiator;
498 }
499 
set_method(base::StringPiece method)500 void URLRequest::set_method(base::StringPiece method) {
501   DCHECK(!is_pending_);
502   method_ = std::string(method);
503 }
504 
505 #if BUILDFLAG(ENABLE_REPORTING)
set_reporting_upload_depth(int reporting_upload_depth)506 void URLRequest::set_reporting_upload_depth(int reporting_upload_depth) {
507   DCHECK(!is_pending_);
508   reporting_upload_depth_ = reporting_upload_depth;
509 }
510 #endif
511 
SetReferrer(base::StringPiece referrer)512 void URLRequest::SetReferrer(base::StringPiece referrer) {
513   DCHECK(!is_pending_);
514   GURL referrer_url(referrer);
515   if (referrer_url.is_valid()) {
516     referrer_ = referrer_url.GetAsReferrer().spec();
517   } else {
518     referrer_ = std::string(referrer);
519   }
520 }
521 
set_referrer_policy(ReferrerPolicy referrer_policy)522 void URLRequest::set_referrer_policy(ReferrerPolicy referrer_policy) {
523   DCHECK(!is_pending_);
524   referrer_policy_ = referrer_policy;
525 }
526 
set_allow_credentials(bool allow_credentials)527 void URLRequest::set_allow_credentials(bool allow_credentials) {
528   allow_credentials_ = allow_credentials;
529   if (allow_credentials) {
530     load_flags_ &= ~LOAD_DO_NOT_SAVE_COOKIES;
531   } else {
532     load_flags_ |= LOAD_DO_NOT_SAVE_COOKIES;
533   }
534 }
535 
Start()536 void URLRequest::Start() {
537   DCHECK(delegate_);
538 
539   if (status_ != OK)
540     return;
541 
542   if (context_->require_network_isolation_key())
543     DCHECK(!isolation_info_.IsEmpty());
544 
545   // Some values can be NULL, but the job factory must not be.
546   DCHECK(context_->job_factory());
547 
548   // Anything that sets |blocked_by_| before start should have cleaned up after
549   // itself.
550   DCHECK(blocked_by_.empty());
551 
552   g_url_requests_started = true;
553   response_info_.request_time = base::Time::Now();
554 
555   load_timing_info_ = LoadTimingInfo();
556   load_timing_info_.request_start_time = response_info_.request_time;
557   load_timing_info_.request_start = base::TimeTicks::Now();
558 
559   if (network_delegate()) {
560     OnCallToDelegate(NetLogEventType::NETWORK_DELEGATE_BEFORE_URL_REQUEST);
561     int error = network_delegate()->NotifyBeforeURLRequest(
562         this,
563         base::BindOnce(&URLRequest::BeforeRequestComplete,
564                        base::Unretained(this)),
565         &delegate_redirect_url_);
566     // If ERR_IO_PENDING is returned, the delegate will invoke
567     // |BeforeRequestComplete| later.
568     if (error != ERR_IO_PENDING)
569       BeforeRequestComplete(error);
570     return;
571   }
572 
573   StartJob(context_->job_factory()->CreateJob(this));
574 }
575 
576 ///////////////////////////////////////////////////////////////////////////////
577 
URLRequest(base::PassKey<URLRequestContext> pass_key,const GURL & url,RequestPriority priority,Delegate * delegate,const URLRequestContext * context,NetworkTrafficAnnotationTag traffic_annotation,bool is_for_websockets,absl::optional<net::NetLogSource> net_log_source)578 URLRequest::URLRequest(base::PassKey<URLRequestContext> pass_key,
579                        const GURL& url,
580                        RequestPriority priority,
581                        Delegate* delegate,
582                        const URLRequestContext* context,
583                        NetworkTrafficAnnotationTag traffic_annotation,
584                        bool is_for_websockets,
585                        absl::optional<net::NetLogSource> net_log_source)
586     : context_(context),
587       net_log_(CreateNetLogWithSource(context->net_log(), net_log_source)),
588       url_chain_(1, url),
589       method_("GET"),
590       delegate_(delegate),
591       is_for_websockets_(is_for_websockets),
592       redirect_limit_(kMaxRedirects),
593       priority_(priority),
594       creation_time_(base::TimeTicks::Now()),
595       traffic_annotation_(traffic_annotation) {
596   // Sanity check out environment.
597   DCHECK(base::SingleThreadTaskRunner::HasCurrentDefault());
598 
599   context->url_requests()->insert(this);
600   net_log_.BeginEvent(NetLogEventType::REQUEST_ALIVE, [&] {
601     return NetLogURLRequestConstructorParams(url, priority_,
602                                              traffic_annotation_);
603   });
604 }
605 
BeforeRequestComplete(int error)606 void URLRequest::BeforeRequestComplete(int error) {
607   DCHECK(!job_.get());
608   DCHECK_NE(ERR_IO_PENDING, error);
609 
610   // Check that there are no callbacks to already failed or canceled requests.
611   DCHECK(!failed());
612 
613   OnCallToDelegateComplete();
614 
615   if (error != OK) {
616     net_log_.AddEventWithStringParams(NetLogEventType::CANCELLED, "source",
617                                       "delegate");
618     StartJob(std::make_unique<URLRequestErrorJob>(this, error));
619   } else if (!delegate_redirect_url_.is_empty()) {
620     GURL new_url;
621     new_url.Swap(&delegate_redirect_url_);
622 
623     StartJob(std::make_unique<URLRequestRedirectJob>(
624         this, new_url,
625         // Use status code 307 to preserve the method, so POST requests work.
626         RedirectUtil::ResponseCode::REDIRECT_307_TEMPORARY_REDIRECT,
627         "Delegate"));
628   } else {
629     StartJob(context_->job_factory()->CreateJob(this));
630   }
631 }
632 
StartJob(std::unique_ptr<URLRequestJob> job)633 void URLRequest::StartJob(std::unique_ptr<URLRequestJob> job) {
634   DCHECK(!is_pending_);
635   DCHECK(!job_);
636   if (is_created_from_network_anonymization_key_) {
637     DCHECK(load_flags_ & LOAD_DISABLE_CACHE);
638     DCHECK(!allow_credentials_);
639   }
640 
641   net_log_.BeginEvent(NetLogEventType::URL_REQUEST_START_JOB, [&] {
642     return NetLogURLRequestStartParams(
643         url(), method_, load_flags_, isolation_info_, site_for_cookies_,
644         initiator_,
645         upload_data_stream_ ? upload_data_stream_->identifier() : -1);
646   });
647 
648   job_ = std::move(job);
649   job_->SetExtraRequestHeaders(extra_request_headers_);
650   job_->SetPriority(priority_);
651   job_->SetRequestHeadersCallback(request_headers_callback_);
652   job_->SetEarlyResponseHeadersCallback(early_response_headers_callback_);
653   job_->SetResponseHeadersCallback(response_headers_callback_);
654 
655   if (upload_data_stream_.get())
656     job_->SetUpload(upload_data_stream_.get());
657 
658   is_pending_ = true;
659   is_redirecting_ = false;
660 
661   response_info_.was_cached = false;
662 
663   maybe_sent_cookies_.clear();
664   maybe_stored_cookies_.clear();
665 
666   GURL referrer_url(referrer_);
667   bool same_origin_for_metrics;
668 
669   if (referrer_url !=
670       URLRequestJob::ComputeReferrerForPolicy(
671           referrer_policy_, referrer_url, url(), &same_origin_for_metrics)) {
672     if (!network_delegate() ||
673         !network_delegate()->CancelURLRequestWithPolicyViolatingReferrerHeader(
674             *this, url(), referrer_url)) {
675       referrer_.clear();
676     } else {
677       // We need to clear the referrer anyway to avoid an infinite recursion
678       // when starting the error job.
679       referrer_.clear();
680       net_log_.AddEventWithStringParams(NetLogEventType::CANCELLED, "source",
681                                         "delegate");
682       RestartWithJob(
683           std::make_unique<URLRequestErrorJob>(this, ERR_BLOCKED_BY_CLIENT));
684       return;
685     }
686   }
687 
688   RecordReferrerGranularityMetrics(same_origin_for_metrics);
689 
690   // Start() always completes asynchronously.
691   //
692   // Status is generally set by URLRequestJob itself, but Start() calls
693   // directly into the URLRequestJob subclass, so URLRequestJob can't set it
694   // here.
695   // TODO(mmenke):  Make the URLRequest manage its own status.
696   status_ = ERR_IO_PENDING;
697   job_->Start();
698 }
699 
RestartWithJob(std::unique_ptr<URLRequestJob> job)700 void URLRequest::RestartWithJob(std::unique_ptr<URLRequestJob> job) {
701   DCHECK(job->request() == this);
702   PrepareToRestart();
703   StartJob(std::move(job));
704 }
705 
Cancel()706 int URLRequest::Cancel() {
707   return DoCancel(ERR_ABORTED, SSLInfo());
708 }
709 
CancelWithError(int error)710 int URLRequest::CancelWithError(int error) {
711   return DoCancel(error, SSLInfo());
712 }
713 
CancelWithSSLError(int error,const SSLInfo & ssl_info)714 void URLRequest::CancelWithSSLError(int error, const SSLInfo& ssl_info) {
715   // This should only be called on a started request.
716   if (!is_pending_ || !job_.get() || job_->has_response_started()) {
717     NOTREACHED();
718     return;
719   }
720   DoCancel(error, ssl_info);
721 }
722 
DoCancel(int error,const SSLInfo & ssl_info)723 int URLRequest::DoCancel(int error, const SSLInfo& ssl_info) {
724   DCHECK_LT(error, 0);
725   // If cancelled while calling a delegate, clear delegate info.
726   if (calling_delegate_) {
727     LogUnblocked();
728     OnCallToDelegateComplete();
729   }
730 
731   // If the URL request already has an error status, then canceling is a no-op.
732   // Plus, we don't want to change the error status once it has been set.
733   if (!failed()) {
734     status_ = error;
735     response_info_.ssl_info = ssl_info;
736 
737     // If the request hasn't already been completed, log a cancellation event.
738     if (!has_notified_completion_) {
739       // Don't log an error code on ERR_ABORTED, since that's redundant.
740       net_log_.AddEventWithNetErrorCode(NetLogEventType::CANCELLED,
741                                         error == ERR_ABORTED ? OK : error);
742     }
743   }
744 
745   if (is_pending_ && job_.get())
746     job_->Kill();
747 
748   // We need to notify about the end of this job here synchronously. The
749   // Job sends an asynchronous notification but by the time this is processed,
750   // our |context_| is NULL.
751   NotifyRequestCompleted();
752 
753   // The Job will call our NotifyDone method asynchronously.  This is done so
754   // that the Delegate implementation can call Cancel without having to worry
755   // about being called recursively.
756 
757   return status_;
758 }
759 
Read(IOBuffer * dest,int dest_size)760 int URLRequest::Read(IOBuffer* dest, int dest_size) {
761   DCHECK(job_.get());
762   DCHECK_NE(ERR_IO_PENDING, status_);
763 
764   // If this is the first read, end the delegate call that may have started in
765   // OnResponseStarted.
766   OnCallToDelegateComplete();
767 
768   // If the request has failed, Read() will return actual network error code.
769   if (status_ != OK)
770     return status_;
771 
772   // This handles reads after the request already completed successfully.
773   // TODO(ahendrickson): DCHECK() that it is not done after
774   // http://crbug.com/115705 is fixed.
775   if (job_->is_done())
776     return status_;
777 
778   if (dest_size == 0) {
779     // Caller is not too bright.  I guess we've done what they asked.
780     return OK;
781   }
782 
783   // Caller should provide a buffer.
784   DCHECK(dest && dest->data());
785 
786   int rv = job_->Read(dest, dest_size);
787   if (rv == ERR_IO_PENDING) {
788     set_status(ERR_IO_PENDING);
789   } else if (rv <= 0) {
790     NotifyRequestCompleted();
791   }
792 
793   // If rv is not 0 or actual bytes read, the status cannot be success.
794   DCHECK(rv >= 0 || status_ != OK);
795   return rv;
796 }
797 
set_status(int status)798 void URLRequest::set_status(int status) {
799   DCHECK_LE(status, 0);
800   DCHECK(!failed() || (status != OK && status != ERR_IO_PENDING));
801   status_ = status;
802 }
803 
failed() const804 bool URLRequest::failed() const {
805   return (status_ != OK && status_ != ERR_IO_PENDING);
806 }
807 
NotifyConnected(const TransportInfo & info,CompletionOnceCallback callback)808 int URLRequest::NotifyConnected(const TransportInfo& info,
809                                 CompletionOnceCallback callback) {
810   OnCallToDelegate(NetLogEventType::URL_REQUEST_DELEGATE_CONNECTED);
811   int result = delegate_->OnConnected(
812       this, info,
813       base::BindOnce(
814           [](URLRequest* request, CompletionOnceCallback callback, int result) {
815             request->OnCallToDelegateComplete(result);
816             std::move(callback).Run(result);
817           },
818           this, std::move(callback)));
819   if (result != ERR_IO_PENDING)
820     OnCallToDelegateComplete(result);
821   return result;
822 }
823 
NotifyReceivedRedirect(const RedirectInfo & redirect_info,bool * defer_redirect)824 void URLRequest::NotifyReceivedRedirect(const RedirectInfo& redirect_info,
825                                         bool* defer_redirect) {
826   DCHECK_EQ(OK, status_);
827   is_redirecting_ = true;
828   OnCallToDelegate(NetLogEventType::URL_REQUEST_DELEGATE_RECEIVED_REDIRECT);
829   delegate_->OnReceivedRedirect(this, redirect_info, defer_redirect);
830   // |this| may be have been destroyed here.
831 }
832 
NotifyResponseStarted(int net_error)833 void URLRequest::NotifyResponseStarted(int net_error) {
834   DCHECK_LE(net_error, 0);
835 
836   // Change status if there was an error.
837   if (net_error != OK)
838     set_status(net_error);
839 
840   // |status_| should not be ERR_IO_PENDING when calling into the
841   // URLRequest::Delegate().
842   DCHECK_NE(ERR_IO_PENDING, status_);
843 
844   net_log_.EndEventWithNetErrorCode(NetLogEventType::URL_REQUEST_START_JOB,
845                                     net_error);
846 
847   // In some cases (e.g. an event was canceled), we might have sent the
848   // completion event and receive a NotifyResponseStarted() later.
849   if (!has_notified_completion_ && net_error == OK) {
850     if (network_delegate())
851       network_delegate()->NotifyResponseStarted(this, net_error);
852   }
853 
854   // Notify in case the entire URL Request has been finished.
855   if (!has_notified_completion_ && net_error != OK)
856     NotifyRequestCompleted();
857 
858   OnCallToDelegate(NetLogEventType::URL_REQUEST_DELEGATE_RESPONSE_STARTED);
859   delegate_->OnResponseStarted(this, net_error);
860   // Nothing may appear below this line as OnResponseStarted may delete
861   // |this|.
862 }
863 
FollowDeferredRedirect(const absl::optional<std::vector<std::string>> & removed_headers,const absl::optional<net::HttpRequestHeaders> & modified_headers)864 void URLRequest::FollowDeferredRedirect(
865     const absl::optional<std::vector<std::string>>& removed_headers,
866     const absl::optional<net::HttpRequestHeaders>& modified_headers) {
867   DCHECK(job_.get());
868   DCHECK_EQ(OK, status_);
869 
870   maybe_sent_cookies_.clear();
871   maybe_stored_cookies_.clear();
872 
873   status_ = ERR_IO_PENDING;
874   job_->FollowDeferredRedirect(removed_headers, modified_headers);
875 }
876 
SetAuth(const AuthCredentials & credentials)877 void URLRequest::SetAuth(const AuthCredentials& credentials) {
878   DCHECK(job_.get());
879   DCHECK(job_->NeedsAuth());
880 
881   maybe_sent_cookies_.clear();
882   maybe_stored_cookies_.clear();
883 
884   status_ = ERR_IO_PENDING;
885   job_->SetAuth(credentials);
886 }
887 
CancelAuth()888 void URLRequest::CancelAuth() {
889   DCHECK(job_.get());
890   DCHECK(job_->NeedsAuth());
891 
892   status_ = ERR_IO_PENDING;
893   job_->CancelAuth();
894 }
895 
ContinueWithCertificate(scoped_refptr<X509Certificate> client_cert,scoped_refptr<SSLPrivateKey> client_private_key)896 void URLRequest::ContinueWithCertificate(
897     scoped_refptr<X509Certificate> client_cert,
898     scoped_refptr<SSLPrivateKey> client_private_key) {
899   DCHECK(job_.get());
900 
901   // Matches the call in NotifyCertificateRequested.
902   OnCallToDelegateComplete();
903 
904   status_ = ERR_IO_PENDING;
905   job_->ContinueWithCertificate(std::move(client_cert),
906                                 std::move(client_private_key));
907 }
908 
ContinueDespiteLastError()909 void URLRequest::ContinueDespiteLastError() {
910   DCHECK(job_.get());
911 
912   // Matches the call in NotifySSLCertificateError.
913   OnCallToDelegateComplete();
914 
915   status_ = ERR_IO_PENDING;
916   job_->ContinueDespiteLastError();
917 }
918 
AbortAndCloseConnection()919 void URLRequest::AbortAndCloseConnection() {
920   DCHECK_EQ(OK, status_);
921   DCHECK(!has_notified_completion_);
922   DCHECK(job_);
923   job_->CloseConnectionOnDestruction();
924   job_.reset();
925 }
926 
PrepareToRestart()927 void URLRequest::PrepareToRestart() {
928   DCHECK(job_.get());
929 
930   // Close the current URL_REQUEST_START_JOB, since we will be starting a new
931   // one.
932   net_log_.EndEvent(NetLogEventType::URL_REQUEST_START_JOB);
933 
934   job_.reset();
935 
936   response_info_ = HttpResponseInfo();
937   response_info_.request_time = base::Time::Now();
938 
939   load_timing_info_ = LoadTimingInfo();
940   load_timing_info_.request_start_time = response_info_.request_time;
941   load_timing_info_.request_start = base::TimeTicks::Now();
942 
943   status_ = OK;
944   is_pending_ = false;
945   proxy_server_ = ProxyServer();
946 }
947 
Redirect(const RedirectInfo & redirect_info,const absl::optional<std::vector<std::string>> & removed_headers,const absl::optional<net::HttpRequestHeaders> & modified_headers)948 void URLRequest::Redirect(
949     const RedirectInfo& redirect_info,
950     const absl::optional<std::vector<std::string>>& removed_headers,
951     const absl::optional<net::HttpRequestHeaders>& modified_headers) {
952   // This method always succeeds. Whether |job_| is allowed to redirect to
953   // |redirect_info| is checked in URLRequestJob::CanFollowRedirect, before
954   // NotifyReceivedRedirect. This means the delegate can assume that, if it
955   // accepted the redirect, future calls to OnResponseStarted correspond to
956   // |redirect_info.new_url|.
957   OnCallToDelegateComplete();
958   if (net_log_.IsCapturing()) {
959     net_log_.AddEventWithStringParams(
960         NetLogEventType::URL_REQUEST_REDIRECTED, "location",
961         redirect_info.new_url.possibly_invalid_spec());
962   }
963 
964   if (network_delegate())
965     network_delegate()->NotifyBeforeRedirect(this, redirect_info.new_url);
966 
967   if (!final_upload_progress_.position() && upload_data_stream_)
968     final_upload_progress_ = upload_data_stream_->GetUploadProgress();
969   PrepareToRestart();
970 
971   bool clear_body = false;
972   net::RedirectUtil::UpdateHttpRequest(url(), method_, redirect_info,
973                                        removed_headers, modified_headers,
974                                        &extra_request_headers_, &clear_body);
975   if (clear_body)
976     upload_data_stream_.reset();
977 
978   method_ = redirect_info.new_method;
979   referrer_ = redirect_info.new_referrer;
980   referrer_policy_ = redirect_info.new_referrer_policy;
981   site_for_cookies_ = redirect_info.new_site_for_cookies;
982   isolation_info_ = isolation_info_.CreateForRedirect(
983       url::Origin::Create(redirect_info.new_url));
984 
985   url_chain_.push_back(redirect_info.new_url);
986   --redirect_limit_;
987 
988   Start();
989 }
990 
991 // static
DefaultCanUseCookies()992 bool URLRequest::DefaultCanUseCookies() {
993   return g_default_can_use_cookies;
994 }
995 
context() const996 const URLRequestContext* URLRequest::context() const {
997   return context_;
998 }
999 
network_delegate() const1000 NetworkDelegate* URLRequest::network_delegate() const {
1001   return context_->network_delegate();
1002 }
1003 
GetExpectedContentSize() const1004 int64_t URLRequest::GetExpectedContentSize() const {
1005   int64_t expected_content_size = -1;
1006   if (job_.get())
1007     expected_content_size = job_->expected_content_size();
1008 
1009   return expected_content_size;
1010 }
1011 
SetPriority(RequestPriority priority)1012 void URLRequest::SetPriority(RequestPriority priority) {
1013   DCHECK_GE(priority, MINIMUM_PRIORITY);
1014   DCHECK_LE(priority, MAXIMUM_PRIORITY);
1015 
1016   if ((load_flags_ & LOAD_IGNORE_LIMITS) && (priority != MAXIMUM_PRIORITY)) {
1017     NOTREACHED();
1018     // Maintain the invariant that requests with IGNORE_LIMITS set
1019     // have MAXIMUM_PRIORITY for release mode.
1020     return;
1021   }
1022 
1023   if (priority_ == priority)
1024     return;
1025 
1026   priority_ = priority;
1027   net_log_.AddEventWithStringParams(NetLogEventType::URL_REQUEST_SET_PRIORITY,
1028                                     "priority",
1029                                     RequestPriorityToString(priority_));
1030   if (job_.get())
1031     job_->SetPriority(priority_);
1032 }
1033 
SetPriorityIncremental(bool priority_incremental)1034 void URLRequest::SetPriorityIncremental(bool priority_incremental) {
1035   priority_incremental_ = priority_incremental;
1036 }
1037 
NotifyAuthRequired(std::unique_ptr<AuthChallengeInfo> auth_info)1038 void URLRequest::NotifyAuthRequired(
1039     std::unique_ptr<AuthChallengeInfo> auth_info) {
1040   DCHECK_EQ(OK, status_);
1041   DCHECK(auth_info);
1042   // Check that there are no callbacks to already failed or cancelled requests.
1043   DCHECK(!failed());
1044 
1045   delegate_->OnAuthRequired(this, *auth_info.get());
1046 }
1047 
NotifyCertificateRequested(SSLCertRequestInfo * cert_request_info)1048 void URLRequest::NotifyCertificateRequested(
1049     SSLCertRequestInfo* cert_request_info) {
1050   status_ = OK;
1051 
1052   OnCallToDelegate(NetLogEventType::URL_REQUEST_DELEGATE_CERTIFICATE_REQUESTED);
1053   delegate_->OnCertificateRequested(this, cert_request_info);
1054 }
1055 
NotifySSLCertificateError(int net_error,const SSLInfo & ssl_info,bool fatal)1056 void URLRequest::NotifySSLCertificateError(int net_error,
1057                                            const SSLInfo& ssl_info,
1058                                            bool fatal) {
1059   status_ = OK;
1060   OnCallToDelegate(NetLogEventType::URL_REQUEST_DELEGATE_SSL_CERTIFICATE_ERROR);
1061   delegate_->OnSSLCertificateError(this, net_error, ssl_info, fatal);
1062 }
1063 
CanSetCookie(const net::CanonicalCookie & cookie,CookieOptions * options) const1064 bool URLRequest::CanSetCookie(const net::CanonicalCookie& cookie,
1065                               CookieOptions* options) const {
1066   DCHECK(!(load_flags_ & LOAD_DO_NOT_SAVE_COOKIES));
1067   bool can_set_cookies = g_default_can_use_cookies;
1068   if (network_delegate()) {
1069     can_set_cookies = network_delegate()->CanSetCookie(*this, cookie, options);
1070   }
1071   if (!can_set_cookies)
1072     net_log_.AddEvent(NetLogEventType::COOKIE_SET_BLOCKED_BY_NETWORK_DELEGATE);
1073   return can_set_cookies;
1074 }
1075 
NotifyReadCompleted(int bytes_read)1076 void URLRequest::NotifyReadCompleted(int bytes_read) {
1077   if (bytes_read > 0)
1078     set_status(OK);
1079   // Notify in case the entire URL Request has been finished.
1080   if (bytes_read <= 0)
1081     NotifyRequestCompleted();
1082 
1083   // When URLRequestJob notices there was an error in URLRequest's |status_|,
1084   // it calls this method with |bytes_read| set to -1. Set it to a real error
1085   // here.
1086   // TODO(maksims): NotifyReadCompleted take the error code as an argument on
1087   // failure, rather than -1.
1088   if (bytes_read == -1) {
1089     // |status_| should indicate an error.
1090     DCHECK(failed());
1091     bytes_read = status_;
1092   }
1093 
1094   delegate_->OnReadCompleted(this, bytes_read);
1095 
1096   // Nothing below this line as OnReadCompleted may delete |this|.
1097 }
1098 
OnHeadersComplete()1099 void URLRequest::OnHeadersComplete() {
1100   // The URLRequest status should still be IO_PENDING, which it was set to
1101   // before the URLRequestJob was started.  On error or cancellation, this
1102   // method should not be called.
1103   DCHECK_EQ(ERR_IO_PENDING, status_);
1104   set_status(OK);
1105   // Cache load timing information now, as information will be lost once the
1106   // socket is closed and the ClientSocketHandle is Reset, which will happen
1107   // once the body is complete.  The start times should already be populated.
1108   if (job_.get()) {
1109     // Keep a copy of the two times the URLRequest sets.
1110     base::TimeTicks request_start = load_timing_info_.request_start;
1111     base::Time request_start_time = load_timing_info_.request_start_time;
1112 
1113     // Clear load times.  Shouldn't be neded, but gives the GetLoadTimingInfo a
1114     // consistent place to start from.
1115     load_timing_info_ = LoadTimingInfo();
1116     job_->GetLoadTimingInfo(&load_timing_info_);
1117 
1118     load_timing_info_.request_start = request_start;
1119     load_timing_info_.request_start_time = request_start_time;
1120 
1121     ConvertRealLoadTimesToBlockingTimes(&load_timing_info_);
1122   }
1123 }
1124 
NotifyRequestCompleted()1125 void URLRequest::NotifyRequestCompleted() {
1126   // TODO(battre): Get rid of this check, according to willchan it should
1127   // not be needed.
1128   if (has_notified_completion_)
1129     return;
1130 
1131   is_pending_ = false;
1132   is_redirecting_ = false;
1133   has_notified_completion_ = true;
1134   if (network_delegate())
1135     network_delegate()->NotifyCompleted(this, job_.get() != nullptr, status_);
1136 }
1137 
OnCallToDelegate(NetLogEventType type)1138 void URLRequest::OnCallToDelegate(NetLogEventType type) {
1139   DCHECK(!calling_delegate_);
1140   DCHECK(blocked_by_.empty());
1141   calling_delegate_ = true;
1142   delegate_event_type_ = type;
1143   net_log_.BeginEvent(type);
1144 }
1145 
OnCallToDelegateComplete(int error)1146 void URLRequest::OnCallToDelegateComplete(int error) {
1147   // This should have been cleared before resuming the request.
1148   DCHECK(blocked_by_.empty());
1149   if (!calling_delegate_)
1150     return;
1151   calling_delegate_ = false;
1152   net_log_.EndEventWithNetErrorCode(delegate_event_type_, error);
1153   delegate_event_type_ = NetLogEventType::FAILED;
1154 }
1155 
RecordReferrerGranularityMetrics(bool request_is_same_origin) const1156 void URLRequest::RecordReferrerGranularityMetrics(
1157     bool request_is_same_origin) const {
1158   GURL referrer_url(referrer_);
1159   bool referrer_more_descriptive_than_its_origin =
1160       referrer_url.is_valid() && referrer_url.PathForRequestPiece().size() > 1;
1161 
1162   // To avoid renaming the existing enum, we have to use the three-argument
1163   // histogram macro.
1164   if (request_is_same_origin) {
1165     UMA_HISTOGRAM_ENUMERATION(
1166         "Net.URLRequest.ReferrerPolicyForRequest.SameOrigin", referrer_policy_,
1167         static_cast<int>(ReferrerPolicy::MAX) + 1);
1168     UMA_HISTOGRAM_BOOLEAN(
1169         "Net.URLRequest.ReferrerHasInformativePath.SameOrigin",
1170         referrer_more_descriptive_than_its_origin);
1171   } else {
1172     UMA_HISTOGRAM_ENUMERATION(
1173         "Net.URLRequest.ReferrerPolicyForRequest.CrossOrigin", referrer_policy_,
1174         static_cast<int>(ReferrerPolicy::MAX) + 1);
1175     UMA_HISTOGRAM_BOOLEAN(
1176         "Net.URLRequest.ReferrerHasInformativePath.CrossOrigin",
1177         referrer_more_descriptive_than_its_origin);
1178   }
1179 }
1180 
CreateIsolationInfoFromNetworkAnonymizationKey(const NetworkAnonymizationKey & network_anonymization_key)1181 IsolationInfo URLRequest::CreateIsolationInfoFromNetworkAnonymizationKey(
1182     const NetworkAnonymizationKey& network_anonymization_key) {
1183   if (!network_anonymization_key.IsFullyPopulated()) {
1184     return IsolationInfo();
1185   }
1186 
1187   url::Origin top_frame_origin =
1188       network_anonymization_key.GetTopFrameSite()->site_as_origin_;
1189 
1190   absl::optional<url::Origin> frame_origin;
1191   if (network_anonymization_key.IsCrossSite()) {
1192     // If we know that the origin is cross site to the top level site, create an
1193     // empty origin to use as the frame origin for the isolation info. This
1194     // should be cross site with the top level origin.
1195     frame_origin = url::Origin();
1196   } else {
1197     // If we don't know that it's cross site to the top level site, use the top
1198     // frame site to set the frame origin.
1199     frame_origin = top_frame_origin;
1200   }
1201 
1202   auto isolation_info = IsolationInfo::Create(
1203       IsolationInfo::RequestType::kOther, top_frame_origin,
1204       frame_origin.value(), SiteForCookies(),
1205       /*party_context=*/absl::nullopt, network_anonymization_key.GetNonce());
1206   // TODO(crbug/1343856): DCHECK isolation info is fully populated.
1207   return isolation_info;
1208 }
1209 
GetConnectionAttempts() const1210 ConnectionAttempts URLRequest::GetConnectionAttempts() const {
1211   if (job_)
1212     return job_->GetConnectionAttempts();
1213   return {};
1214 }
1215 
SetRequestHeadersCallback(RequestHeadersCallback callback)1216 void URLRequest::SetRequestHeadersCallback(RequestHeadersCallback callback) {
1217   DCHECK(!job_.get());
1218   DCHECK(request_headers_callback_.is_null());
1219   request_headers_callback_ = std::move(callback);
1220 }
1221 
SetResponseHeadersCallback(ResponseHeadersCallback callback)1222 void URLRequest::SetResponseHeadersCallback(ResponseHeadersCallback callback) {
1223   DCHECK(!job_.get());
1224   DCHECK(response_headers_callback_.is_null());
1225   response_headers_callback_ = std::move(callback);
1226 }
1227 
SetEarlyResponseHeadersCallback(ResponseHeadersCallback callback)1228 void URLRequest::SetEarlyResponseHeadersCallback(
1229     ResponseHeadersCallback callback) {
1230   DCHECK(!job_.get());
1231   DCHECK(early_response_headers_callback_.is_null());
1232   early_response_headers_callback_ = std::move(callback);
1233 }
1234 
set_socket_tag(const SocketTag & socket_tag)1235 void URLRequest::set_socket_tag(const SocketTag& socket_tag) {
1236   DCHECK(!is_pending_);
1237   DCHECK(url().SchemeIsHTTPOrHTTPS());
1238   socket_tag_ = socket_tag;
1239 }
1240 
GetWeakPtr()1241 base::WeakPtr<URLRequest> URLRequest::GetWeakPtr() {
1242   return weak_factory_.GetWeakPtr();
1243 }
1244 
1245 }  // namespace net
1246