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