• 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 #ifndef NET_URL_REQUEST_URL_REQUEST_H_
6 #define NET_URL_REQUEST_URL_REQUEST_H_
7 
8 #include <stdint.h>
9 
10 #include <memory>
11 #include <optional>
12 #include <string>
13 #include <string_view>
14 #include <vector>
15 
16 #include "base/containers/flat_set.h"
17 #include "base/memory/raw_ptr.h"
18 #include "base/memory/weak_ptr.h"
19 #include "base/supports_user_data.h"
20 #include "base/threading/thread_checker.h"
21 #include "base/time/time.h"
22 #include "base/types/pass_key.h"
23 #include "base/values.h"
24 #include "net/base/auth.h"
25 #include "net/base/completion_repeating_callback.h"
26 #include "net/base/idempotency.h"
27 #include "net/base/ip_endpoint.h"
28 #include "net/base/isolation_info.h"
29 #include "net/base/load_flags.h"
30 #include "net/base/load_states.h"
31 #include "net/base/load_timing_info.h"
32 #include "net/base/net_error_details.h"
33 #include "net/base/net_errors.h"
34 #include "net/base/net_export.h"
35 #include "net/base/network_delegate.h"
36 #include "net/base/proxy_chain.h"
37 #include "net/base/request_priority.h"
38 #include "net/base/upload_progress.h"
39 #include "net/cookies/canonical_cookie.h"
40 #include "net/cookies/cookie_partition_key.h"
41 #include "net/cookies/cookie_setting_override.h"
42 #include "net/cookies/cookie_util.h"
43 #include "net/cookies/site_for_cookies.h"
44 #include "net/dns/public/secure_dns_policy.h"
45 #include "net/filter/source_stream.h"
46 #include "net/http/http_raw_request_headers.h"
47 #include "net/http/http_request_headers.h"
48 #include "net/http/http_response_headers.h"
49 #include "net/http/http_response_info.h"
50 #include "net/log/net_log_event_type.h"
51 #include "net/log/net_log_source.h"
52 #include "net/log/net_log_with_source.h"
53 #include "net/net_buildflags.h"
54 #include "net/shared_dictionary/shared_dictionary.h"
55 #include "net/shared_dictionary/shared_dictionary_getter.h"
56 #include "net/socket/connection_attempts.h"
57 #include "net/socket/socket_tag.h"
58 #include "net/storage_access_api/status.h"
59 #include "net/traffic_annotation/network_traffic_annotation.h"
60 #include "net/url_request/redirect_info.h"
61 #include "net/url_request/referrer_policy.h"
62 #include "url/gurl.h"
63 #include "url/origin.h"
64 
65 namespace net {
66 
67 class CookieOptions;
68 class CookieInclusionStatus;
69 class IOBuffer;
70 struct LoadTimingInfo;
71 struct RedirectInfo;
72 class SSLCertRequestInfo;
73 class SSLInfo;
74 class SSLPrivateKey;
75 struct TransportInfo;
76 class UploadDataStream;
77 class URLRequestContext;
78 class URLRequestJob;
79 class X509Certificate;
80 
81 namespace device_bound_sessions {
82 struct SessionKey;
83 }
84 
85 //-----------------------------------------------------------------------------
86 // A class  representing the asynchronous load of a data stream from an URL.
87 //
88 // The lifetime of an instance of this class is completely controlled by the
89 // consumer, and the instance is not required to live on the heap or be
90 // allocated in any special way.  It is also valid to delete an URLRequest
91 // object during the handling of a callback to its delegate.  Of course, once
92 // the URLRequest is deleted, no further callbacks to its delegate will occur.
93 //
94 // NOTE: All usage of all instances of this class should be on the same thread.
95 //
96 class NET_EXPORT URLRequest : public base::SupportsUserData {
97  public:
98   // Max number of http redirects to follow. The Fetch spec says: "If
99   // request's redirect count is twenty, return a network error."
100   // https://fetch.spec.whatwg.org/#http-redirect-fetch
101   static constexpr int kMaxRedirects = 20;
102 
103   // The delegate's methods are called from the message loop of the thread
104   // on which the request's Start() method is called. See above for the
105   // ordering of callbacks.
106   //
107   // The callbacks will be called in the following order:
108   //   Start()
109   //    - OnConnected* (zero or more calls, see method comment)
110   //    - OnCertificateRequested* (zero or more calls, if the SSL server and/or
111   //      SSL proxy requests a client certificate for authentication)
112   //    - OnSSLCertificateError* (zero or one call, if the SSL server's
113   //      certificate has an error)
114   //    - OnReceivedRedirect* (zero or more calls, for the number of redirects)
115   //    - OnAuthRequired* (zero or more calls, for the number of
116   //      authentication failures)
117   //    - OnResponseStarted
118   //   Read() initiated by delegate
119   //    - OnReadCompleted* (zero or more calls until all data is read)
120   //
121   // Read() must be called at least once. Read() returns bytes read when it
122   // completes immediately, and a negative error value if an IO is pending or if
123   // there is an error.
124   class NET_EXPORT Delegate {
125    public:
126     Delegate() = default;
127 
128     // Forbid copy and assign to prevent slicing.
129     Delegate(const Delegate&) = delete;
130     Delegate& operator=(const Delegate&) = delete;
131 
132     // Called each time a connection is obtained, before any data is sent.
133     //
134     // |request| is never nullptr. Caller retains ownership.
135     //
136     // |info| describes the newly-obtained connection.
137     //
138     // This may be called several times if the request creates multiple HTTP
139     // transactions, e.g. if the request is redirected. It may also be called
140     // several times per transaction, e.g. if the connection is retried, after
141     // each HTTP auth challenge, or for split HTTP range requests.
142     //
143     // If this returns an error, the transaction will stop. The transaction
144     // will continue when the |callback| is run. If run with an error, the
145     // transaction will fail.
146     virtual int OnConnected(URLRequest* request,
147                             const TransportInfo& info,
148                             CompletionOnceCallback callback);
149 
150     // Called upon receiving a redirect.  The delegate may call the request's
151     // Cancel method to prevent the redirect from being followed.  Since there
152     // may be multiple chained redirects, there may also be more than one
153     // redirect call.
154     //
155     // When this function is called, the request will still contain the
156     // original URL, the destination of the redirect is provided in
157     // |redirect_info.new_url|.  If the delegate does not cancel the request
158     // and |*defer_redirect| is false, then the redirect will be followed, and
159     // the request's URL will be changed to the new URL.  Otherwise if the
160     // delegate does not cancel the request and |*defer_redirect| is true, then
161     // the redirect will be followed once FollowDeferredRedirect is called
162     // on the URLRequest.
163     //
164     // The caller must set |*defer_redirect| to false, so that delegates do not
165     // need to set it if they are happy with the default behavior of not
166     // deferring redirect.
167     virtual void OnReceivedRedirect(URLRequest* request,
168                                     const RedirectInfo& redirect_info,
169                                     bool* defer_redirect);
170 
171     // Called when we receive an authentication failure.  The delegate should
172     // call request->SetAuth() with the user's credentials once it obtains them,
173     // or request->CancelAuth() to cancel the login and display the error page.
174     // When it does so, the request will be reissued, restarting the sequence
175     // of On* callbacks.
176     //
177     // NOTE: If auth_info.scheme is AUTH_SCHEME_NEGOTIATE on ChromeOS, this
178     // method should not call SetAuth(). Instead, it should show ChromeOS
179     // specific UI and cancel the request. (See b/260522530).
180     virtual void OnAuthRequired(URLRequest* request,
181                                 const AuthChallengeInfo& auth_info);
182 
183     // Called when we receive an SSL CertificateRequest message for client
184     // authentication.  The delegate should call
185     // request->ContinueWithCertificate() with the client certificate the user
186     // selected and its private key, or request->ContinueWithCertificate(NULL,
187     // NULL)
188     // to continue the SSL handshake without a client certificate.
189     virtual void OnCertificateRequested(URLRequest* request,
190                                         SSLCertRequestInfo* cert_request_info);
191 
192     // Called when using SSL and the server responds with a certificate with
193     // an error, for example, whose common name does not match the common name
194     // we were expecting for that host.  The delegate should either do the
195     // safe thing and Cancel() the request or decide to proceed by calling
196     // ContinueDespiteLastError().  cert_error is a ERR_* error code
197     // indicating what's wrong with the certificate.
198     // If |fatal| is true then the host in question demands a higher level
199     // of security (due e.g. to HTTP Strict Transport Security, user
200     // preference, or built-in policy). In this case, errors must not be
201     // bypassable by the user.
202     virtual void OnSSLCertificateError(URLRequest* request,
203                                        int net_error,
204                                        const SSLInfo& ssl_info,
205                                        bool fatal);
206 
207     // After calling Start(), the delegate will receive an OnResponseStarted
208     // callback when the request has completed. |net_error| will be set to OK
209     // or an actual net error.  On success, all redirects have been
210     // followed and the final response is beginning to arrive.  At this point,
211     // meta data about the response is available, including for example HTTP
212     // response headers if this is a request for a HTTP resource.
213     virtual void OnResponseStarted(URLRequest* request, int net_error);
214 
215     // Called when the a Read of the response body is completed after an
216     // IO_PENDING status from a Read() call.
217     // The data read is filled into the buffer which the caller passed
218     // to Read() previously.
219     //
220     // If an error occurred, |bytes_read| will be set to the error.
221     virtual void OnReadCompleted(URLRequest* request, int bytes_read) = 0;
222 
223    protected:
224     virtual ~Delegate() = default;
225   };
226 
227   // URLRequests are always created by calling URLRequestContext::CreateRequest.
228   URLRequest(base::PassKey<URLRequestContext> pass_key,
229              const GURL& url,
230              RequestPriority priority,
231              Delegate* delegate,
232              const URLRequestContext* context,
233              NetworkTrafficAnnotationTag traffic_annotation,
234              bool is_for_websockets,
235              std::optional<net::NetLogSource> net_log_source);
236 
237   URLRequest(const URLRequest&) = delete;
238   URLRequest& operator=(const URLRequest&) = delete;
239 
240   // If destroyed after Start() has been called but while IO is pending,
241   // then the request will be effectively canceled and the delegate
242   // will not have any more of its methods called.
243   ~URLRequest() override;
244 
245   // Changes the default cookie policy from allowing all cookies to blocking all
246   // cookies. Embedders that want to implement a more flexible policy should
247   // change the default to blocking all cookies, and provide a NetworkDelegate
248   // with the URLRequestContext that maintains the CookieStore.
249   // The cookie policy default has to be set before the first URLRequest is
250   // started. Once it was set to block all cookies, it cannot be changed back.
251   static void SetDefaultCookiePolicyToBlock();
252 
253   // The original url is the url used to initialize the request, and it may
254   // differ from the url if the request was redirected.
original_url()255   const GURL& original_url() const { return url_chain_.front(); }
256   // The chain of urls traversed by this request.  If the request had no
257   // redirects, this vector will contain one element.
url_chain()258   const std::vector<GURL>& url_chain() const { return url_chain_; }
url()259   const GURL& url() const { return url_chain_.back(); }
260 
261   // Explicitly set the URL chain for this request.  This can be used to
262   // indicate a chain of redirects that happen at a layer above the network
263   // service; e.g. navigation redirects.
264   //
265   // Note, the last entry in the new `url_chain` will be ignored.  Instead
266   // the request will preserve its current URL.  This is done since the higher
267   // layer providing the explicit `url_chain` may not be aware of modifications
268   // to the request URL by throttles.
269   //
270   // This method should only be called on new requests that have a single
271   // entry in their existing `url_chain_`.
272   void SetURLChain(const std::vector<GURL>& url_chain);
273 
274   // The URL that should be consulted for the third-party cookie blocking
275   // policy, as defined in Section 2.1.1 and 2.1.2 of
276   // https://tools.ietf.org/html/draft-ietf-httpbis-cookie-same-site.
277   //
278   // WARNING: This URL must only be used for the third-party cookie blocking
279   //          policy. It MUST NEVER be used for any kind of SECURITY check.
280   //
281   //          For example, if a top-level navigation is redirected, the
282   //          first-party for cookies will be the URL of the first URL in the
283   //          redirect chain throughout the whole redirect. If it was used for
284   //          a security check, an attacker might try to get around this check
285   //          by starting from some page that redirects to the
286   //          host-to-be-attacked.
287   //
site_for_cookies()288   const SiteForCookies& site_for_cookies() const { return site_for_cookies_; }
289   // This method may only be called before Start().
290   void set_site_for_cookies(const SiteForCookies& site_for_cookies);
291 
292   // Sets IsolationInfo for the request, which affects whether SameSite cookies
293   // are sent, what NetworkAnonymizationKey is used for cached resources, and
294   // how that behavior changes when following redirects. This may only be
295   // changed before Start() is called. Setting this value causes the
296   // cookie_partition_key_ to be recalculated. When the isolation information is
297   // set through a redirect, the request_site used to create the partition key
298   // should come from the new_url associated with the redirect_info object
299   // associated with the redirect to ensure the cookie partition key's ancestor
300   // chain bit is set correctly.
301   //
302   // TODO(crbug.com/40093296): This isn't actually used yet for SameSite
303   // cookies. Update consumers and fix that.
304   void set_isolation_info(
305       const IsolationInfo& isolation_info,
306       std::optional<GURL> redirect_info_new_url = std::nullopt);
307 
308   // This will convert the passed NetworkAnonymizationKey to an IsolationInfo.
309   // This IsolationInfo mmay be assigned an inaccurate frame origin because the
310   // NetworkAnonymizationKey might not contain all the information to populate
311   // it. Additionally the NetworkAnonymizationKey uses sites which will be
312   // converted to origins when set on the IsolationInfo. If using this method it
313   // is required to skip the cache and not use credentials. Before starting the
314   // request, it must have the LoadFlag LOAD_DISABLE_CACHE set, and must be set
315   // to not allow credentials, to ensure that the inaccurate frame origin has no
316   // impact. The request will DCHECK otherwise.
317   void set_isolation_info_from_network_anonymization_key(
318       const NetworkAnonymizationKey& network_anonymization_key);
319 
isolation_info()320   const IsolationInfo& isolation_info() const { return isolation_info_; }
321 
cookie_partition_key()322   const std::optional<CookiePartitionKey>& cookie_partition_key() const {
323     return cookie_partition_key_;
324   }
325 
326   // Indicate whether SameSite cookies should be attached even though the
327   // request is cross-site.
force_ignore_site_for_cookies()328   bool force_ignore_site_for_cookies() const {
329     return force_ignore_site_for_cookies_;
330   }
set_force_ignore_site_for_cookies(bool attach)331   void set_force_ignore_site_for_cookies(bool attach) {
332     force_ignore_site_for_cookies_ = attach;
333   }
334 
335   // Indicates if the request should be treated as a main frame navigation for
336   // SameSite cookie computations.  This flag overrides the IsolationInfo
337   // request type associated with fetches from a service worker context.
force_main_frame_for_same_site_cookies()338   bool force_main_frame_for_same_site_cookies() const {
339     return force_main_frame_for_same_site_cookies_;
340   }
set_force_main_frame_for_same_site_cookies(bool value)341   void set_force_main_frame_for_same_site_cookies(bool value) {
342     force_main_frame_for_same_site_cookies_ = value;
343   }
344 
345   // Overrides pertaining to cookie settings for this particular request.
cookie_setting_overrides()346   CookieSettingOverrides& cookie_setting_overrides() {
347     return cookie_setting_overrides_;
348   }
cookie_setting_overrides()349   const CookieSettingOverrides& cookie_setting_overrides() const {
350     return cookie_setting_overrides_;
351   }
352 
353   // The first-party URL policy to apply when updating the first party URL
354   // during redirects. The first-party URL policy may only be changed before
355   // Start() is called.
first_party_url_policy()356   RedirectInfo::FirstPartyURLPolicy first_party_url_policy() const {
357     return first_party_url_policy_;
358   }
359   void set_first_party_url_policy(
360       RedirectInfo::FirstPartyURLPolicy first_party_url_policy);
361 
362   // The origin of the context which initiated the request. This is distinct
363   // from the "first party for cookies" discussed above in a number of ways:
364   //
365   // 1. The request's initiator does not change during a redirect. If a form
366   //    submission from `https://example.com/` redirects through a number of
367   //    sites before landing on `https://not-example.com/`, the initiator for
368   //    each of those requests will be `https://example.com/`.
369   //
370   // 2. The request's initiator is the origin of the frame or worker which made
371   //    the request, even for top-level navigations. That is, if
372   //    `https://example.com/`'s form submission is made in the top-level frame,
373   //    the first party for cookies would be the target URL's origin. The
374   //    initiator remains `https://example.com/`.
375   //
376   // This value is used to perform the cross-origin check specified in Section
377   // 4.3 of https://tools.ietf.org/html/draft-ietf-httpbis-cookie-same-site.
378   //
379   // Note: the initiator can be null for browser-initiated top level
380   // navigations. This is different from a unique Origin (e.g. in sandboxed
381   // iframes).
initiator()382   const std::optional<url::Origin>& initiator() const { return initiator_; }
383   // This method may only be called before Start().
384   void set_initiator(const std::optional<url::Origin>& initiator);
385 
386   // The request method.  "GET" is the default value. The request method may
387   // only be changed before Start() is called. Request methods are
388   // case-sensitive, so standard HTTP methods like GET or POST should be
389   // specified in uppercase.
method()390   const std::string& method() const { return method_; }
391   void set_method(std::string_view method);
392 
393 #if BUILDFLAG(ENABLE_REPORTING)
394   // Reporting upload nesting depth of this request.
395   //
396   // If the request is not a Reporting upload, the depth is 0.
397   //
398   // If the request is a Reporting upload, the depth is the max of the depth
399   // of the requests reported within it plus 1. (Non-NEL reports are
400   // considered to have depth 0.)
reporting_upload_depth()401   int reporting_upload_depth() const { return reporting_upload_depth_; }
402   void set_reporting_upload_depth(int reporting_upload_depth);
403 #endif
404 
405   // The referrer URL for the request
referrer()406   const std::string& referrer() const { return referrer_; }
407   // Sets the referrer URL for the request. Can only be changed before Start()
408   // is called. |referrer| is sanitized to remove URL fragment, user name and
409   // password. If a referrer policy is set via set_referrer_policy(), then
410   // |referrer| should obey the policy; if it doesn't, it will be cleared when
411   // the request is started. The referrer URL may be suppressed or changed
412   // during the course of the request, for example because of a referrer policy
413   // set with set_referrer_policy().
414   void SetReferrer(std::string_view referrer);
415 
416   // The referrer policy to apply when updating the referrer during redirects.
417   // The referrer policy may only be changed before Start() is called. Any
418   // referrer set via SetReferrer() is expected to obey the policy set via
419   // set_referrer_policy(); otherwise the referrer will be cleared when the
420   // request is started.
referrer_policy()421   ReferrerPolicy referrer_policy() const { return referrer_policy_; }
422   void set_referrer_policy(ReferrerPolicy referrer_policy);
423 
424   // Sets whether credentials are allowed.
425   // If credentials are allowed, the request will send and save HTTP
426   // cookies, as well as authentication to the origin server. If not,
427   // they will not be sent, however proxy-level authentication will
428   // still occur. Setting this will force the LOAD_DO_NOT_SAVE_COOKIES field to
429   // be set in |load_flags_|. See https://crbug.com/799935.
430   void set_allow_credentials(bool allow_credentials);
allow_credentials()431   bool allow_credentials() const { return allow_credentials_; }
432 
433   // Sets the upload data.
434   void set_upload(std::unique_ptr<UploadDataStream> upload);
435 
436   // Gets the upload data.
437   const UploadDataStream* get_upload_for_testing() const;
438 
439   // Returns true if the request has a non-empty message body to upload.
440   bool has_upload() const;
441 
442   // Set or remove a extra request header.  These methods may only be called
443   // before Start() is called, or between receiving a redirect and trying to
444   // follow it.
445   void SetExtraRequestHeaderByName(std::string_view name,
446                                    std::string_view value,
447                                    bool overwrite);
448   void RemoveRequestHeaderByName(std::string_view name);
449 
450   // Sets all extra request headers.  Any extra request headers set by other
451   // methods are overwritten by this method.  This method may only be called
452   // before Start() is called.  It is an error to call it later.
453   void SetExtraRequestHeaders(const HttpRequestHeaders& headers);
454 
extra_request_headers()455   const HttpRequestHeaders& extra_request_headers() const {
456     return extra_request_headers_;
457   }
458 
459   // Gets the total amount of data received from network after SSL decoding and
460   // proxy handling. Pertains only to the last URLRequestJob issued by this
461   // URLRequest, i.e. reset on redirects, but not reset when multiple roundtrips
462   // are used for range requests or auth.
463   int64_t GetTotalReceivedBytes() const;
464 
465   // Gets the total amount of data sent over the network before SSL encoding and
466   // proxy handling. Pertains only to the last URLRequestJob issued by this
467   // URLRequest, i.e. reset on redirects, but not reset when multiple roundtrips
468   // are used for range requests or auth.
469   int64_t GetTotalSentBytes() const;
470 
471   // The size of the response body before removing any content encodings.
472   // Does not include redirects or sub-requests issued at lower levels (range
473   // requests or auth). Only includes bytes which have been read so far,
474   // including bytes from the cache.
475   int64_t GetRawBodyBytes() const;
476 
477   // Returns the current load state for the request. The returned value's
478   // |param| field is an optional parameter describing details related to the
479   // load state. Not all load states have a parameter.
480   LoadStateWithParam GetLoadState() const;
481 
482   // Returns a partial representation of the request's state as a value, for
483   // debugging.
484   base::Value::Dict GetStateAsValue() const;
485 
486   // Logs information about the what external object currently blocking the
487   // request.  LogUnblocked must be called before resuming the request.  This
488   // can be called multiple times in a row either with or without calling
489   // LogUnblocked between calls.  |blocked_by| must not be empty.
490   void LogBlockedBy(std::string_view blocked_by);
491 
492   // Just like LogBlockedBy, but also makes GetLoadState return source as the
493   // |param| in the value returned by GetLoadState.  Calling LogUnblocked or
494   // LogBlockedBy will clear the load param.  |blocked_by| must not be empty.
495   void LogAndReportBlockedBy(std::string_view blocked_by);
496 
497   // Logs that the request is no longer blocked by the last caller to
498   // LogBlockedBy.
499   void LogUnblocked();
500 
501   // Returns the current upload progress in bytes. When the upload data is
502   // chunked, size is set to zero, but position will not be.
503   UploadProgress GetUploadProgress() const;
504 
505   // Get response header(s) by name.  This method may only be called
506   // once the delegate's OnResponseStarted method has been called.  Headers
507   // that appear more than once in the response are coalesced, with values
508   // separated by commas (per RFC 2616). This will not work with cookies since
509   // comma can be used in cookie values.
510   std::string GetResponseHeaderByName(std::string_view name) const;
511 
512   // The time when |this| was constructed.
creation_time()513   base::TimeTicks creation_time() const { return creation_time_; }
514 
515   // The time at which the returned response was requested.  For cached
516   // responses, this is the last time the cache entry was validated.
request_time()517   const base::Time& request_time() const { return response_info_.request_time; }
518 
519   // The time at which the returned response was generated.  For cached
520   // responses, this is the last time the cache entry was validated.
response_time()521   const base::Time& response_time() const {
522     return response_info_.response_time;
523   }
524 
525   // Like response_time, but ignoring revalidations.
original_response_time()526   const base::Time& original_response_time() const {
527     return response_info_.original_response_time;
528   }
529 
530   // Indicate if this response was fetched from disk cache.
was_cached()531   bool was_cached() const { return response_info_.was_cached; }
532 
533   // Returns true if the URLRequest was delivered over SPDY.
was_fetched_via_spdy()534   bool was_fetched_via_spdy() const {
535     return response_info_.was_fetched_via_spdy;
536   }
537 
538   // Returns the host and port that the content was fetched from.  See
539   // http_response_info.h for caveats relating to cached content.
540   IPEndPoint GetResponseRemoteEndpoint() const;
541 
542   // Get all response headers, as a HttpResponseHeaders object.  See comments
543   // in HttpResponseHeaders class as to the format of the data.
544   HttpResponseHeaders* response_headers() const;
545 
546   // Get the SSL connection info.
ssl_info()547   const SSLInfo& ssl_info() const { return response_info_.ssl_info; }
548 
549   const std::optional<AuthChallengeInfo>& auth_challenge_info() const;
550 
551   // Gets timing information related to the request.  Events that have not yet
552   // occurred are left uninitialized.  After a second request starts, due to
553   // a redirect or authentication, values will be reset.
554   //
555   // LoadTimingInfo only contains ConnectTiming information and socket IDs for
556   // non-cached HTTP responses.
557   void GetLoadTimingInfo(LoadTimingInfo* load_timing_info) const;
558 
559   // Gets the networkd error details of the most recent origin that the network
560   // stack makes the request to.
561   void PopulateNetErrorDetails(NetErrorDetails* details) const;
562 
563   // Gets the remote endpoint of the most recent socket that the network stack
564   // used to make this request.
565   //
566   // Note that GetResponseRemoteEndpoint returns the |socket_address| field from
567   // HttpResponseInfo, which is only populated once the response headers are
568   // received, and can return cached values for cache revalidation requests.
569   // GetTransactionRemoteEndpoint will only return addresses from the current
570   // request.
571   //
572   // Returns true and fills in |endpoint| if the endpoint is available; returns
573   // false and leaves |endpoint| unchanged if it is unavailable.
574   bool GetTransactionRemoteEndpoint(IPEndPoint* endpoint) const;
575 
576   // Get the mime type.  This method may only be called once the delegate's
577   // OnResponseStarted method has been called.
578   void GetMimeType(std::string* mime_type) const;
579 
580   // Get the charset (character encoding).  This method may only be called once
581   // the delegate's OnResponseStarted method has been called.
582   void GetCharset(std::string* charset) const;
583 
584   // Returns the HTTP response code (e.g., 200, 404, and so on).  This method
585   // may only be called once the delegate's OnResponseStarted method has been
586   // called.  For non-HTTP requests, this method returns -1.
587   int GetResponseCode() const;
588 
589   // Get the HTTP response info in its entirety.
response_info()590   const HttpResponseInfo& response_info() const { return response_info_; }
591 
592   // Access the LOAD_* flags modifying this request (see load_flags.h).
load_flags()593   int load_flags() const { return partial_load_flags_ | per_hop_load_flags_; }
594 
is_created_from_network_anonymization_key()595   bool is_created_from_network_anonymization_key() const {
596     return is_created_from_network_anonymization_key_;
597   }
598 
599   // Returns the Secure DNS Policy for the request.
secure_dns_policy()600   SecureDnsPolicy secure_dns_policy() const { return secure_dns_policy_; }
601 
602   void set_maybe_sent_cookies(CookieAccessResultList cookies);
603   void set_maybe_stored_cookies(CookieAndLineAccessResultList cookies);
604 
605   // These lists contain a list of cookies that are associated with the given
606   // request, both those that were sent and accepted, and those that were
607   // removed or flagged from the request before use. The status indicates
608   // whether they were actually used (INCLUDE), or the reason they were removed
609   // or flagged. They are cleared on redirects and other request restarts that
610   // cause sent cookies to be recomputed / new cookies to potentially be
611   // received (such as calling SetAuth() to send HTTP auth credentials, but not
612   // calling ContinueWithCertification() to respond to client cert challenges),
613   // and only contain the cookies relevant to the most recent roundtrip.
614 
615   // Populated while the http request is being built.
maybe_sent_cookies()616   const CookieAccessResultList& maybe_sent_cookies() const {
617     return maybe_sent_cookies_;
618   }
619   // Populated after the response headers are received.
maybe_stored_cookies()620   const CookieAndLineAccessResultList& maybe_stored_cookies() const {
621     return maybe_stored_cookies_;
622   }
623 
624   // The new flags may change the IGNORE_LIMITS flag only when called
625   // before Start() is called, it must only set the flag, and if set,
626   // the priority of this request must already be MAXIMUM_PRIORITY.
627   void SetLoadFlags(int flags);
628 
629   // Sets "temporary" load flags. They are cleared upon receiving a redirect.
set_per_hop_load_flags(int flags)630   void set_per_hop_load_flags(int flags) { per_hop_load_flags_ = flags; }
631 
632   // Controls the Secure DNS behavior to use when creating the socket for this
633   // request.
634   void SetSecureDnsPolicy(SecureDnsPolicy secure_dns_policy);
635 
636   // Returns true if the request is "pending" (i.e., if Start() has been called,
637   // and the response has not yet been called).
is_pending()638   bool is_pending() const { return is_pending_; }
639 
640   // Returns true if the request is in the process of redirecting to a new
641   // URL but has not yet initiated the new request.
is_redirecting()642   bool is_redirecting() const { return is_redirecting_; }
643 
644   // This method is called to start the request.  The delegate will receive
645   // a OnResponseStarted callback when the request is started.  The request
646   // must have a delegate set before this method is called.
647   void Start();
648 
649   // This method may be called at any time after Start() has been called to
650   // cancel the request.  This method may be called many times, and it has
651   // no effect once the response has completed.  It is guaranteed that no
652   // methods of the delegate will be called after the request has been
653   // cancelled, except that this may call the delegate's OnReadCompleted()
654   // during the call to Cancel itself. Returns |ERR_ABORTED| or other net error
655   // if there was one.
656   int Cancel();
657 
658   // Cancels the request and sets the error to |error|, unless the request
659   // already failed with another error code (see net_error_list.h). Returns
660   // final network error code.
661   int CancelWithError(int error);
662 
663   // Cancels the request and sets the error to |error| (see net_error_list.h
664   // for values) and attaches |ssl_info| as the SSLInfo for that request.  This
665   // is useful to attach a certificate and certificate error to a canceled
666   // request.
667   void CancelWithSSLError(int error, const SSLInfo& ssl_info);
668 
669   // Read initiates an asynchronous read from the response, and must only be
670   // called after the OnResponseStarted callback is received with a net::OK. If
671   // data is available, length and the data will be returned immediately. If the
672   // request has failed, an error code will be returned. If data is not yet
673   // available, Read returns net::ERR_IO_PENDING, and the Delegate's
674   // OnReadComplete method will be called asynchronously with the result of the
675   // read, unless the URLRequest is canceled.
676   //
677   // The |buf| parameter is a buffer to receive the data. If the operation
678   // completes asynchronously, the implementation will reference the buffer
679   // until OnReadComplete is called. The buffer must be at least |max_bytes| in
680   // length.
681   //
682   // The |max_bytes| parameter is the maximum number of bytes to read.
683   int Read(IOBuffer* buf, int max_bytes);
684 
685   // This method may be called to follow a redirect that was deferred in
686   // response to an OnReceivedRedirect call. If non-null,
687   // |modified_headers| are changes applied to the request headers after
688   // updating them for the redirect.
689   void FollowDeferredRedirect(
690       const std::optional<std::vector<std::string>>& removed_headers,
691       const std::optional<net::HttpRequestHeaders>& modified_headers);
692 
693   // One of the following two methods should be called in response to an
694   // OnAuthRequired() callback (and only then).
695   // SetAuth will reissue the request with the given credentials.
696   // CancelAuth will give up and display the error page.
697   void SetAuth(const AuthCredentials& credentials);
698   void CancelAuth();
699 
700   // This method can be called after the user selects a client certificate to
701   // instruct this URLRequest to continue with the request with the
702   // certificate.  Pass NULL if the user doesn't have a client certificate.
703   void ContinueWithCertificate(scoped_refptr<X509Certificate> client_cert,
704                                scoped_refptr<SSLPrivateKey> client_private_key);
705 
706   // This method can be called after some error notifications to instruct this
707   // URLRequest to ignore the current error and continue with the request.  To
708   // cancel the request instead, call Cancel().
709   void ContinueDespiteLastError();
710 
711   // Aborts the request (without invoking any completion callbacks) and closes
712   // the current connection, rather than returning it to the socket pool. Only
713   // affects HTTP/1.1 connections and tunnels.
714   //
715   // Intended to be used in cases where socket reuse can potentially leak data
716   // across sites.
717   //
718   // May only be called after Delegate::OnResponseStarted() has been invoked
719   // with net::OK, but before the body has been completely read. After the last
720   // body has been read, the socket may have already been handed off to another
721   // consumer.
722   //
723   // Due to transactions potentially being shared by multiple URLRequests in
724   // some cases, it is possible the socket may not be immediately closed, but
725   // will instead be closed when all URLRequests sharing the socket have been
726   // destroyed.
727   void AbortAndCloseConnection();
728 
729   // Used to specify the context (cookie store, cache) for this request.
730   const URLRequestContext* context() const;
731 
732   // Returns context()->network_delegate().
733   NetworkDelegate* network_delegate() const;
734 
net_log()735   const NetLogWithSource& net_log() const { return net_log_; }
736 
737   // Returns the expected content size if available
738   int64_t GetExpectedContentSize() const;
739 
740   // Returns the priority level for this request.
priority()741   RequestPriority priority() const { return priority_; }
742 
743   // Returns the incremental loading priority flag for this request.
priority_incremental()744   bool priority_incremental() const { return priority_incremental_; }
745 
746   // Sets the priority level for this request and any related
747   // jobs. Must not change the priority to anything other than
748   // MAXIMUM_PRIORITY if the IGNORE_LIMITS load flag is set.
749   void SetPriority(RequestPriority priority);
750 
751   // Sets the incremental priority flag for this request.
752   void SetPriorityIncremental(bool priority_incremental);
753 
set_received_response_content_length(int64_t received_content_length)754   void set_received_response_content_length(int64_t received_content_length) {
755     received_response_content_length_ = received_content_length;
756   }
757 
758   // The number of bytes in the raw response body (before any decompression,
759   // etc.). This is only available after the final Read completes.
received_response_content_length()760   int64_t received_response_content_length() const {
761     return received_response_content_length_;
762   }
763 
764   // Available when the request headers are sent, which is before the more
765   // general response_info() is available.
proxy_chain()766   const ProxyChain& proxy_chain() const { return proxy_chain_; }
767 
768   // Gets the connection attempts made in the process of servicing this
769   // URLRequest. Only guaranteed to be valid if called after the request fails
770   // or after the response headers are received.
771   ConnectionAttempts GetConnectionAttempts() const;
772 
traffic_annotation()773   const NetworkTrafficAnnotationTag& traffic_annotation() const {
774     return traffic_annotation_;
775   }
776 
777   const std::optional<base::flat_set<net::SourceStream::SourceType>>&
accepted_stream_types()778   accepted_stream_types() const {
779     return accepted_stream_types_;
780   }
781 
set_accepted_stream_types(const std::optional<base::flat_set<net::SourceStream::SourceType>> & types)782   void set_accepted_stream_types(
783       const std::optional<base::flat_set<net::SourceStream::SourceType>>&
784           types) {
785     if (types) {
786       DCHECK(!types->contains(net::SourceStream::SourceType::TYPE_NONE));
787       DCHECK(!types->contains(net::SourceStream::SourceType::TYPE_UNKNOWN));
788     }
789     accepted_stream_types_ = types;
790   }
791 
792   // Sets a callback that will be invoked each time the request is about to
793   // be actually sent and will receive actual request headers that are about
794   // to hit the wire, including SPDY/QUIC internal headers.
795   //
796   // Can only be set once before the request is started.
797   void SetRequestHeadersCallback(RequestHeadersCallback callback);
798 
799   // Sets a callback that will be invoked each time the response is received
800   // from the remote party with the actual response headers received. Note this
801   // is different from response_headers() getter in that in case of revalidation
802   // request, the latter will return cached headers, while the callback will be
803   // called with a response from the server.
804   void SetResponseHeadersCallback(ResponseHeadersCallback callback);
805 
806   // Sets a callback that will be invoked each time a 103 Early Hints response
807   // is received from the remote party.
808   void SetEarlyResponseHeadersCallback(ResponseHeadersCallback callback);
809 
810   // Set a callback that will be invoked when a matching shared dictionary is
811   // available to determine whether it is allowed to use the dictionary.
812   void SetIsSharedDictionaryReadAllowedCallback(
813       base::RepeatingCallback<bool()> callback);
814 
815   // Set a callback that will be invoked each time a device bound
816   // session is accessed as part of this URL request. Because device
817   // bound sessions can be accessed asynchronously after this request
818   // completes, this callback must be able to safely outlive `this`.
819   void SetDeviceBoundSessionAccessCallback(
820       base::RepeatingCallback<void(const device_bound_sessions::SessionKey&)>
821           callback);
822   base::RepeatingCallback<void(const device_bound_sessions::SessionKey&)>
device_bound_session_access_callback()823   device_bound_session_access_callback() {
824     return device_bound_session_access_callback_;
825   }
826 
827   // Sets socket tag to be applied to all sockets used to execute this request.
828   // Must be set before Start() is called.  Only currently supported for HTTP
829   // and HTTPS requests on Android; UID tagging requires
830   // MODIFY_NETWORK_ACCOUNTING permission.
831   // NOTE(pauljensen): Setting a tag disallows sharing of sockets with requests
832   // with other tags, which may adversely effect performance by prohibiting
833   // connection sharing. In other words use of multiplexed sockets (e.g. HTTP/2
834   // and QUIC) will only be allowed if all requests have the same socket tag.
835   void set_socket_tag(const SocketTag& socket_tag);
socket_tag()836   const SocketTag& socket_tag() const { return socket_tag_; }
837 
838   // |upgrade_if_insecure| should be set to true if this request (including
839   // redirects) should be upgraded to HTTPS due to an Upgrade-Insecure-Requests
840   // requirement.
set_upgrade_if_insecure(bool upgrade_if_insecure)841   void set_upgrade_if_insecure(bool upgrade_if_insecure) {
842     upgrade_if_insecure_ = upgrade_if_insecure;
843   }
upgrade_if_insecure()844   bool upgrade_if_insecure() const { return upgrade_if_insecure_; }
845 
846   // `ad_tagged` should be set to true if the request is thought to be related
847   // to advertising.
set_ad_tagged(bool ad_tagged)848   void set_ad_tagged(bool ad_tagged) { ad_tagged_ = ad_tagged; }
ad_tagged()849   bool ad_tagged() const { return ad_tagged_; }
850 
851   // By default, client certs will be sent (provided via
852   // Delegate::OnCertificateRequested) when cookies are disabled
853   // (LOAD_DO_NOT_SEND_COOKIES / LOAD_DO_NOT_SAVE_COOKIES). As described at
854   // https://crbug.com/775438, this is not the desired behavior. When
855   // |send_client_certs| is set to false, this will suppress the
856   // Delegate::OnCertificateRequested callback when cookies/credentials are also
857   // suppressed. This method has no effect if credentials are enabled (cookies
858   // saved and sent).
859   // TODO(crbug.com/40089326): Remove this when the underlying
860   // issue is fixed.
set_send_client_certs(bool send_client_certs)861   void set_send_client_certs(bool send_client_certs) {
862     send_client_certs_ = send_client_certs;
863   }
send_client_certs()864   bool send_client_certs() const { return send_client_certs_; }
865 
is_for_websockets()866   bool is_for_websockets() const { return is_for_websockets_; }
867 
SetIdempotency(Idempotency idempotency)868   void SetIdempotency(Idempotency idempotency) { idempotency_ = idempotency; }
GetIdempotency()869   Idempotency GetIdempotency() const { return idempotency_; }
870 
871   // Set a SharedDictionaryGetter which will be used to get a shared dictionary
872   // for this request. This must not be called after Start() is called.
873   void SetSharedDictionaryGetter(
874       SharedDictionaryGetter shared_dictionary_getter);
875 
set_storage_access_status(std::optional<cookie_util::StorageAccessStatus> status)876   void set_storage_access_status(
877       std::optional<cookie_util::StorageAccessStatus> status) {
878     storage_access_status_ = status;
879   }
880 
881   // Returns the StorageAccessStatus for this request.
882   // TODO(https://crbug.com/366284840): move this state out of //net (into
883   // network::URLLoader) to respect layering rules.
storage_access_status()884   std::optional<cookie_util::StorageAccessStatus> storage_access_status()
885       const {
886     return storage_access_status_;
887   }
888 
889   static bool DefaultCanUseCookies();
890 
891   // Calculates the StorageAccessStatus for this request, according to the
892   // NetworkDelegate. Also records metrics.
893   // TODO(https://crbug.com/366284840): Move this to URLLoader once the
894   // "Activate-Storage-Access: retry" header is handled in URLLoader.
895   std::optional<net::cookie_util::StorageAccessStatus>
896   CalculateStorageAccessStatus(
897       base::optional_ref<const RedirectInfo> redirect_info =
898           base::optional_ref<const RedirectInfo>(std::nullopt)) const;
899 
900   base::WeakPtr<URLRequest> GetWeakPtr();
901 
902  protected:
903   // Allow the URLRequestJob class to control the is_pending() flag.
set_is_pending(bool value)904   void set_is_pending(bool value) { is_pending_ = value; }
905 
906   // Setter / getter for the status of the request. Status is represented as a
907   // net::Error code. See |status_|.
status()908   int status() const { return status_; }
909   void set_status(int status);
910 
911   // Returns true if the request failed or was cancelled.
912   bool failed() const;
913 
914   // Returns the error status of the request.
915 
916   // Allow the URLRequestJob to redirect this request. If non-null,
917   // |removed_headers| and |modified_headers| are changes
918   // applied to the request headers after updating them for the redirect.
919   void Redirect(const RedirectInfo& redirect_info,
920                 const std::optional<std::vector<std::string>>& removed_headers,
921                 const std::optional<net::HttpRequestHeaders>& modified_headers);
922 
923   // Allow the URLRequestJob to retry this request, after having activated
924   // Storage Access (if possible).
925   void RetryWithStorageAccess();
926 
927   // Called by URLRequestJob when a redirect occurs. Notifies delegates, and
928   // follows the redirect (possibly asynchronously), unless they block it.
929   void ReceivedRedirect(RedirectInfo redirect_info);
930 
931  private:
932   friend class URLRequestJob;
933 
934   // For testing purposes.
935   // TODO(maksims): Remove this.
936   friend class TestNetworkDelegate;
937 
938   // Resumes or blocks a request paused by the NetworkDelegate::OnBeforeRequest
939   // handler. If |blocked| is true, the request is blocked and an error page is
940   // returned indicating so. This should only be called after Start is called
941   // and OnBeforeRequest returns true (signalling that the request should be
942   // paused).
943   void BeforeRequestComplete(int error);
944 
945   void StartJob(std::unique_ptr<URLRequestJob> job);
946 
947   // Restarting involves replacing the current job with a new one such as what
948   // happens when following a HTTP redirect.
949   void RestartWithJob(std::unique_ptr<URLRequestJob> job);
950   void PrepareToRestart();
951 
952   // Cancels the request and set the error and ssl info for this request to the
953   // passed values. Returns the error that was set.
954   int DoCancel(int error, const SSLInfo& ssl_info);
955 
956   // Called by the URLRequestJob when the headers are received, before any other
957   // method, to allow caching of load timing information.
958   void OnHeadersComplete();
959 
960   // Notifies the network delegate that the request has been completed.
961   // This does not imply a successful completion. Also a canceled request is
962   // considered completed.
963   void NotifyRequestCompleted();
964 
965   // Called by URLRequestJob to allow interception when the final response
966   // occurs.
967   void NotifyResponseStarted(int net_error);
968 
969   // These functions delegate to |delegate_|.  See URLRequest::Delegate for the
970   // meaning of these functions.
971   int NotifyConnected(const TransportInfo& info,
972                       CompletionOnceCallback callback);
973   void NotifyAuthRequired(std::unique_ptr<AuthChallengeInfo> auth_info);
974   void NotifyCertificateRequested(SSLCertRequestInfo* cert_request_info);
975   void NotifySSLCertificateError(int net_error,
976                                  const SSLInfo& ssl_info,
977                                  bool fatal);
978   void NotifyReadCompleted(int bytes_read);
979 
980   // This function delegates to the NetworkDelegate if it is not nullptr.
981   // Otherwise, cookies can be used unless SetDefaultCookiePolicyToBlock() has
982   // been called.
983   bool CanSetCookie(const net::CanonicalCookie& cookie,
984                     CookieOptions* options,
985                     const net::FirstPartySetMetadata& first_party_set_metadata,
986                     CookieInclusionStatus* inclusion_status) const;
987 
988   // Called just before calling a delegate that may block a request. |type|
989   // should be the delegate's event type,
990   // e.g. NetLogEventType::NETWORK_DELEGATE_AUTH_REQUIRED.
991   void OnCallToDelegate(NetLogEventType type);
992   // Called when the delegate lets a request continue.  Also called on
993   // cancellation. `error` is an optional error code associated with
994   // completion. It's only for logging purposes, and will not directly cancel
995   // the request if it's a value other than OK.
996   void OnCallToDelegateComplete(int error = OK);
997 
998   // Records the referrer policy of the given request, bucketed by
999   // whether the request is same-origin or not. To save computation,
1000   // takes this fact as a boolean parameter rather than dynamically
1001   // checking.
1002   void RecordReferrerGranularityMetrics(bool request_is_same_origin) const;
1003 
1004   // Creates a partial IsolationInfo with the information accessible from the
1005   // NetworkAnonymiationKey.
1006   net::IsolationInfo CreateIsolationInfoFromNetworkAnonymizationKey(
1007       const NetworkAnonymizationKey& network_anonymization_key);
1008 
1009   // Contextual information used for this request. Cannot be NULL. This contains
1010   // most of the dependencies which are shared between requests (disk cache,
1011   // cookie store, socket pool, etc.)
1012   raw_ptr<const URLRequestContext> context_;
1013 
1014   // Tracks the time spent in various load states throughout this request.
1015   NetLogWithSource net_log_;
1016 
1017   std::unique_ptr<URLRequestJob> job_;
1018   std::unique_ptr<UploadDataStream> upload_data_stream_;
1019 
1020   std::vector<GURL> url_chain_;
1021   SiteForCookies site_for_cookies_;
1022 
1023   IsolationInfo isolation_info_;
1024   // The cookie partition key for the request. Partitioned cookies should be set
1025   // using this key and only partitioned cookies with this partition key should
1026   // be sent. The cookie partition key is optional(nullopt) if cookie
1027   // partitioning is not enabled, or if the NIK has no top-frame site.
1028   //
1029   // Unpartitioned cookies are unaffected by this field.
1030   std::optional<CookiePartitionKey> cookie_partition_key_ = std::nullopt;
1031 
1032   bool force_ignore_site_for_cookies_ = false;
1033   bool force_main_frame_for_same_site_cookies_ = false;
1034   CookieSettingOverrides cookie_setting_overrides_;
1035 
1036   std::optional<url::Origin> initiator_;
1037   GURL delegate_redirect_url_;
1038   std::string method_;  // "GET", "POST", etc. Case-sensitive.
1039   std::string referrer_;
1040   ReferrerPolicy referrer_policy_ =
1041       ReferrerPolicy::CLEAR_ON_TRANSITION_FROM_SECURE_TO_INSECURE;
1042   RedirectInfo::FirstPartyURLPolicy first_party_url_policy_ =
1043       RedirectInfo::FirstPartyURLPolicy::NEVER_CHANGE_URL;
1044   HttpRequestHeaders extra_request_headers_;
1045   // Flags indicating the request type for the load. Expected values are LOAD_*
1046   // enums above.
1047   int partial_load_flags_ = LOAD_NORMAL;
1048   // Load flags that only apply to a single hop in the redirect chain.
1049   int per_hop_load_flags_ = LOAD_NORMAL;
1050 
1051   // Whether the request is allowed to send credentials in general. Set by
1052   // caller.
1053   bool allow_credentials_ = true;
1054   SecureDnsPolicy secure_dns_policy_ = SecureDnsPolicy::kAllow;
1055 
1056   CookieAccessResultList maybe_sent_cookies_;
1057   CookieAndLineAccessResultList maybe_stored_cookies_;
1058 
1059 #if BUILDFLAG(ENABLE_REPORTING)
1060   int reporting_upload_depth_ = 0;
1061 #endif
1062 
1063   // Never access methods of the |delegate_| directly. Always use the
1064   // Notify... methods for this.
1065   raw_ptr<Delegate> delegate_;
1066 
1067   const bool is_for_websockets_;
1068 
1069   // Current error status of the job, as a net::Error code. When the job is
1070   // busy, it is ERR_IO_PENDING. When the job is idle (either completed, or
1071   // awaiting a call from the URLRequestDelegate before continuing the request),
1072   // it is OK. If the request has been cancelled without a specific error, it is
1073   // ERR_ABORTED. And on failure, it's the corresponding error code for that
1074   // error.
1075   //
1076   // |status_| may bounce between ERR_IO_PENDING and OK as a request proceeds,
1077   // but once an error is encountered or the request is canceled, it will take
1078   // the appropriate error code and never change again. If multiple failures
1079   // have been encountered, this will be the first error encountered.
1080   int status_ = OK;
1081 
1082   bool is_created_from_network_anonymization_key_ = false;
1083 
1084   // The HTTP response info, lazily initialized.
1085   HttpResponseInfo response_info_;
1086 
1087   // Tells us whether the job is outstanding. This is true from the time
1088   // Start() is called to the time we dispatch RequestComplete and indicates
1089   // whether the job is active.
1090   bool is_pending_ = false;
1091 
1092   // Indicates if the request is in the process of redirecting to a new
1093   // location.  It is true from the time the headers complete until a
1094   // new request begins.
1095   bool is_redirecting_ = false;
1096 
1097   // Set when a redirect is deferred. Redirects are deferred after validity
1098   // checks are performed, so this field must not be modified.
1099   std::optional<RedirectInfo> deferred_redirect_info_;
1100 
1101   // Number of times we're willing to redirect.  Used to guard against
1102   // infinite redirects.
1103   int redirect_limit_;
1104 
1105   // Cached value for use after we've orphaned the job handling the
1106   // first transaction in a request involving redirects.
1107   UploadProgress final_upload_progress_;
1108 
1109   // The priority level for this request.  Objects like
1110   // ClientSocketPool use this to determine which URLRequest to
1111   // allocate sockets to first.
1112   RequestPriority priority_;
1113 
1114   // The incremental flag for this request that indicates if it should be
1115   // loaded concurrently with other resources of the same priority for
1116   // protocols that support HTTP extensible priorities (RFC 9218).
1117   // Currently only used in HTTP/3.
1118   bool priority_incremental_ = kDefaultPriorityIncremental;
1119 
1120   // If |calling_delegate_| is true, the event type of the delegate being
1121   // called.
1122   NetLogEventType delegate_event_type_ = NetLogEventType::FAILED;
1123 
1124   // True if this request is currently calling a delegate, or is blocked waiting
1125   // for the URL request or network delegate to resume it.
1126   bool calling_delegate_ = false;
1127 
1128   // An optional parameter that provides additional information about what
1129   // |this| is currently being blocked by.
1130   std::string blocked_by_;
1131   bool use_blocked_by_as_load_param_ = false;
1132 
1133   // Safe-guard to ensure that we do not send multiple "I am completed"
1134   // messages to network delegate.
1135   // TODO(battre): Remove this. http://crbug.com/89049
1136   bool has_notified_completion_ = false;
1137 
1138   int64_t received_response_content_length_ = 0;
1139 
1140   base::TimeTicks creation_time_;
1141 
1142   // Timing information for the most recent request.  Its start times are
1143   // populated during Start(), and the rest are populated in OnResponseReceived.
1144   LoadTimingInfo load_timing_info_;
1145 
1146   // The proxy chain used for this request, if any.
1147   ProxyChain proxy_chain_;
1148 
1149   // If not null, the network service will not advertise any stream types
1150   // (via Accept-Encoding) that are not listed. Also, it will not attempt
1151   // decoding any non-listed stream types.
1152   std::optional<base::flat_set<net::SourceStream::SourceType>>
1153       accepted_stream_types_;
1154 
1155   const NetworkTrafficAnnotationTag traffic_annotation_;
1156 
1157   SocketTag socket_tag_;
1158 
1159   // See Set{Request|Response,EarlyResponse}HeadersCallback() above for details.
1160   RequestHeadersCallback request_headers_callback_;
1161   ResponseHeadersCallback early_response_headers_callback_;
1162   ResponseHeadersCallback response_headers_callback_;
1163 
1164   // See SetIsSharedDictionaryReadAllowedCallback() above for details.
1165   base::RepeatingCallback<bool()> is_shared_dictionary_read_allowed_callback_;
1166 
1167   bool upgrade_if_insecure_ = false;
1168 
1169   bool ad_tagged_ = false;
1170 
1171   bool send_client_certs_ = true;
1172 
1173   // Idempotency of the request.
1174   Idempotency idempotency_ = DEFAULT_IDEMPOTENCY;
1175 
1176   SharedDictionaryGetter shared_dictionary_getter_;
1177 
1178   // The storage access status for this request. If this is nullopt, this
1179   // request will not include the Sec-Fetch-Storage-Access header.
1180   std::optional<net::cookie_util::StorageAccessStatus> storage_access_status_;
1181 
1182   base::RepeatingCallback<void(const device_bound_sessions::SessionKey&)>
1183       device_bound_session_access_callback_;
1184 
1185   THREAD_CHECKER(thread_checker_);
1186 
1187   base::WeakPtrFactory<URLRequest> weak_factory_{this};
1188 };
1189 
1190 }  // namespace net
1191 
1192 #endif  // NET_URL_REQUEST_URL_REQUEST_H_
1193