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