url_request.h revision 7dbb3d5cf0c15f500944d211057644d6a2f37371
1// Copyright (c) 2012 The Chromium Authors. All rights reserved. 2// Use of this source code is governed by a BSD-style license that can be 3// found in the LICENSE file. 4 5#ifndef NET_URL_REQUEST_URL_REQUEST_H_ 6#define NET_URL_REQUEST_URL_REQUEST_H_ 7 8#include <string> 9#include <vector> 10 11#include "base/debug/leak_tracker.h" 12#include "base/logging.h" 13#include "base/memory/ref_counted.h" 14#include "base/strings/string16.h" 15#include "base/supports_user_data.h" 16#include "base/threading/non_thread_safe.h" 17#include "base/time/time.h" 18#include "net/base/auth.h" 19#include "net/base/completion_callback.h" 20#include "net/base/load_states.h" 21#include "net/base/load_timing_info.h" 22#include "net/base/net_export.h" 23#include "net/base/net_log.h" 24#include "net/base/network_delegate.h" 25#include "net/base/request_priority.h" 26#include "net/base/upload_progress.h" 27#include "net/cookies/canonical_cookie.h" 28#include "net/http/http_request_headers.h" 29#include "net/http/http_response_info.h" 30#include "net/url_request/url_request_status.h" 31#include "url/gurl.h" 32 33// Temporary layering violation to allow existing users of a deprecated 34// interface. 35class ChildProcessSecurityPolicyTest; 36class TestAutomationProvider; 37class URLRequestAutomationJob; 38 39namespace base { 40namespace debug { 41class StackTrace; 42} 43} 44 45// Temporary layering violation to allow existing users of a deprecated 46// interface. 47namespace appcache { 48class AppCacheInterceptor; 49class AppCacheRequestHandlerTest; 50class AppCacheURLRequestJobTest; 51} 52 53// Temporary layering violation to allow existing users of a deprecated 54// interface. 55namespace content { 56class ResourceDispatcherHostTest; 57} 58 59// Temporary layering violation to allow existing users of a deprecated 60// interface. 61namespace fileapi { 62class FileSystemDirURLRequestJobTest; 63class FileSystemURLRequestJobTest; 64class FileWriterDelegateTest; 65} 66 67// Temporary layering violation to allow existing users of a deprecated 68// interface. 69namespace webkit_blob { 70class BlobURLRequestJobTest; 71} 72 73namespace net { 74 75class CookieOptions; 76class HostPortPair; 77class IOBuffer; 78struct LoadTimingInfo; 79class SSLCertRequestInfo; 80class SSLInfo; 81class UploadDataStream; 82class URLRequestContext; 83class URLRequestJob; 84class X509Certificate; 85 86// This stores the values of the Set-Cookie headers received during the request. 87// Each item in the vector corresponds to a Set-Cookie: line received, 88// excluding the "Set-Cookie:" part. 89typedef std::vector<std::string> ResponseCookies; 90 91//----------------------------------------------------------------------------- 92// A class representing the asynchronous load of a data stream from an URL. 93// 94// The lifetime of an instance of this class is completely controlled by the 95// consumer, and the instance is not required to live on the heap or be 96// allocated in any special way. It is also valid to delete an URLRequest 97// object during the handling of a callback to its delegate. Of course, once 98// the URLRequest is deleted, no further callbacks to its delegate will occur. 99// 100// NOTE: All usage of all instances of this class should be on the same thread. 101// 102class NET_EXPORT URLRequest : NON_EXPORTED_BASE(public base::NonThreadSafe), 103 public base::SupportsUserData { 104 public: 105 // Callback function implemented by protocol handlers to create new jobs. 106 // The factory may return NULL to indicate an error, which will cause other 107 // factories to be queried. If no factory handles the request, then the 108 // default job will be used. 109 typedef URLRequestJob* (ProtocolFactory)(URLRequest* request, 110 NetworkDelegate* network_delegate, 111 const std::string& scheme); 112 113 // HTTP request/response header IDs (via some preprocessor fun) for use with 114 // SetRequestHeaderById and GetResponseHeaderById. 115 enum { 116#define HTTP_ATOM(x) HTTP_ ## x, 117#include "net/http/http_atom_list.h" 118#undef HTTP_ATOM 119 }; 120 121 // Referrer policies (see set_referrer_policy): During server redirects, the 122 // referrer header might be cleared, if the protocol changes from HTTPS to 123 // HTTP. This is the default behavior of URLRequest, corresponding to 124 // CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE. Alternatively, the 125 // referrer policy can be set to never change the referrer header. This 126 // behavior corresponds to NEVER_CLEAR_REFERRER. Embedders will want to use 127 // NEVER_CLEAR_REFERRER when implementing the meta-referrer support 128 // (http://wiki.whatwg.org/wiki/Meta_referrer) and sending requests with a 129 // non-default referrer policy. Only the default referrer policy requires 130 // the referrer to be cleared on transitions from HTTPS to HTTP. 131 enum ReferrerPolicy { 132 CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE, 133 NEVER_CLEAR_REFERRER, 134 }; 135 136 // This class handles network interception. Use with 137 // (Un)RegisterRequestInterceptor. 138 class NET_EXPORT Interceptor { 139 public: 140 virtual ~Interceptor() {} 141 142 // Called for every request made. Should return a new job to handle the 143 // request if it should be intercepted, or NULL to allow the request to 144 // be handled in the normal manner. 145 virtual URLRequestJob* MaybeIntercept( 146 URLRequest* request, NetworkDelegate* network_delegate) = 0; 147 148 // Called after having received a redirect response, but prior to the 149 // the request delegate being informed of the redirect. Can return a new 150 // job to replace the existing job if it should be intercepted, or NULL 151 // to allow the normal handling to continue. If a new job is provided, 152 // the delegate never sees the original redirect response, instead the 153 // response produced by the intercept job will be returned. 154 virtual URLRequestJob* MaybeInterceptRedirect( 155 URLRequest* request, 156 NetworkDelegate* network_delegate, 157 const GURL& location); 158 159 // Called after having received a final response, but prior to the 160 // the request delegate being informed of the response. This is also 161 // called when there is no server response at all to allow interception 162 // on dns or network errors. Can return a new job to replace the existing 163 // job if it should be intercepted, or NULL to allow the normal handling to 164 // continue. If a new job is provided, the delegate never sees the original 165 // response, instead the response produced by the intercept job will be 166 // returned. 167 virtual URLRequestJob* MaybeInterceptResponse( 168 URLRequest* request, NetworkDelegate* network_delegate); 169 }; 170 171 // Deprecated interfaces in net::URLRequest. They have been moved to 172 // URLRequest's private section to prevent new uses. Existing uses are 173 // explicitly friended here and should be removed over time. 174 class NET_EXPORT Deprecated { 175 private: 176 // TODO(willchan): Kill off these friend declarations. 177 friend class ::ChildProcessSecurityPolicyTest; 178 friend class ::TestAutomationProvider; 179 friend class ::URLRequestAutomationJob; 180 friend class TestInterceptor; 181 friend class URLRequestFilter; 182 friend class appcache::AppCacheInterceptor; 183 friend class appcache::AppCacheRequestHandlerTest; 184 friend class appcache::AppCacheURLRequestJobTest; 185 friend class content::ResourceDispatcherHostTest; 186 friend class fileapi::FileSystemDirURLRequestJobTest; 187 friend class fileapi::FileSystemURLRequestJobTest; 188 friend class fileapi::FileWriterDelegateTest; 189 friend class webkit_blob::BlobURLRequestJobTest; 190 191 // Use URLRequestJobFactory::ProtocolHandler instead. 192 static ProtocolFactory* RegisterProtocolFactory(const std::string& scheme, 193 ProtocolFactory* factory); 194 195 // TODO(pauljensen): Remove this when AppCacheInterceptor is a 196 // ProtocolHandler, see crbug.com/161547. 197 static void RegisterRequestInterceptor(Interceptor* interceptor); 198 static void UnregisterRequestInterceptor(Interceptor* interceptor); 199 200 DISALLOW_IMPLICIT_CONSTRUCTORS(Deprecated); 201 }; 202 203 // The delegate's methods are called from the message loop of the thread 204 // on which the request's Start() method is called. See above for the 205 // ordering of callbacks. 206 // 207 // The callbacks will be called in the following order: 208 // Start() 209 // - OnCertificateRequested* (zero or more calls, if the SSL server and/or 210 // SSL proxy requests a client certificate for authentication) 211 // - OnSSLCertificateError* (zero or one call, if the SSL server's 212 // certificate has an error) 213 // - OnReceivedRedirect* (zero or more calls, for the number of redirects) 214 // - OnAuthRequired* (zero or more calls, for the number of 215 // authentication failures) 216 // - OnResponseStarted 217 // Read() initiated by delegate 218 // - OnReadCompleted* (zero or more calls until all data is read) 219 // 220 // Read() must be called at least once. Read() returns true when it completed 221 // immediately, and false if an IO is pending or if there is an error. When 222 // Read() returns false, the caller can check the Request's status() to see 223 // if an error occurred, or if the IO is just pending. When Read() returns 224 // true with zero bytes read, it indicates the end of the response. 225 // 226 class NET_EXPORT Delegate { 227 public: 228 // Called upon a server-initiated redirect. The delegate may call the 229 // request's Cancel method to prevent the redirect from being followed. 230 // Since there may be multiple chained redirects, there may also be more 231 // than one redirect call. 232 // 233 // When this function is called, the request will still contain the 234 // original URL, the destination of the redirect is provided in 'new_url'. 235 // If the delegate does not cancel the request and |*defer_redirect| is 236 // false, then the redirect will be followed, and the request's URL will be 237 // changed to the new URL. Otherwise if the delegate does not cancel the 238 // request and |*defer_redirect| is true, then the redirect will be 239 // followed once FollowDeferredRedirect is called on the URLRequest. 240 // 241 // The caller must set |*defer_redirect| to false, so that delegates do not 242 // need to set it if they are happy with the default behavior of not 243 // deferring redirect. 244 virtual void OnReceivedRedirect(URLRequest* request, 245 const GURL& new_url, 246 bool* defer_redirect); 247 248 // Called when we receive an authentication failure. The delegate should 249 // call request->SetAuth() with the user's credentials once it obtains them, 250 // or request->CancelAuth() to cancel the login and display the error page. 251 // When it does so, the request will be reissued, restarting the sequence 252 // of On* callbacks. 253 virtual void OnAuthRequired(URLRequest* request, 254 AuthChallengeInfo* auth_info); 255 256 // Called when we receive an SSL CertificateRequest message for client 257 // authentication. The delegate should call 258 // request->ContinueWithCertificate() with the client certificate the user 259 // selected, or request->ContinueWithCertificate(NULL) to continue the SSL 260 // handshake without a client certificate. 261 virtual void OnCertificateRequested( 262 URLRequest* request, 263 SSLCertRequestInfo* cert_request_info); 264 265 // Called when using SSL and the server responds with a certificate with 266 // an error, for example, whose common name does not match the common name 267 // we were expecting for that host. The delegate should either do the 268 // safe thing and Cancel() the request or decide to proceed by calling 269 // ContinueDespiteLastError(). cert_error is a ERR_* error code 270 // indicating what's wrong with the certificate. 271 // If |fatal| is true then the host in question demands a higher level 272 // of security (due e.g. to HTTP Strict Transport Security, user 273 // preference, or built-in policy). In this case, errors must not be 274 // bypassable by the user. 275 virtual void OnSSLCertificateError(URLRequest* request, 276 const SSLInfo& ssl_info, 277 bool fatal); 278 279 // After calling Start(), the delegate will receive an OnResponseStarted 280 // callback when the request has completed. If an error occurred, the 281 // request->status() will be set. On success, all redirects have been 282 // followed and the final response is beginning to arrive. At this point, 283 // meta data about the response is available, including for example HTTP 284 // response headers if this is a request for a HTTP resource. 285 virtual void OnResponseStarted(URLRequest* request) = 0; 286 287 // Called when the a Read of the response body is completed after an 288 // IO_PENDING status from a Read() call. 289 // The data read is filled into the buffer which the caller passed 290 // to Read() previously. 291 // 292 // If an error occurred, request->status() will contain the error, 293 // and bytes read will be -1. 294 virtual void OnReadCompleted(URLRequest* request, int bytes_read) = 0; 295 296 protected: 297 virtual ~Delegate() {} 298 }; 299 300 // TODO(shalev): Get rid of this constructor in favour of the one below it. 301 // Initialize an URL request. 302 URLRequest(const GURL& url, 303 Delegate* delegate, 304 const URLRequestContext* context); 305 306 URLRequest(const GURL& url, 307 Delegate* delegate, 308 const URLRequestContext* context, 309 NetworkDelegate* network_delegate); 310 311 // If destroyed after Start() has been called but while IO is pending, 312 // then the request will be effectively canceled and the delegate 313 // will not have any more of its methods called. 314 virtual ~URLRequest(); 315 316 // Changes the default cookie policy from allowing all cookies to blocking all 317 // cookies. Embedders that want to implement a more flexible policy should 318 // change the default to blocking all cookies, and provide a NetworkDelegate 319 // with the URLRequestContext that maintains the CookieStore. 320 // The cookie policy default has to be set before the first URLRequest is 321 // started. Once it was set to block all cookies, it cannot be changed back. 322 static void SetDefaultCookiePolicyToBlock(); 323 324 // Returns true if the scheme can be handled by URLRequest. False otherwise. 325 static bool IsHandledProtocol(const std::string& scheme); 326 327 // Returns true if the url can be handled by URLRequest. False otherwise. 328 // The function returns true for invalid urls because URLRequest knows how 329 // to handle those. 330 // NOTE: This will also return true for URLs that are handled by 331 // ProtocolFactories that only work for requests that are scoped to a 332 // Profile. 333 static bool IsHandledURL(const GURL& url); 334 335 // The original url is the url used to initialize the request, and it may 336 // differ from the url if the request was redirected. 337 const GURL& original_url() const { return url_chain_.front(); } 338 // The chain of urls traversed by this request. If the request had no 339 // redirects, this vector will contain one element. 340 const std::vector<GURL>& url_chain() const { return url_chain_; } 341 const GURL& url() const { return url_chain_.back(); } 342 343 // The URL that should be consulted for the third-party cookie blocking 344 // policy. 345 // 346 // WARNING: This URL must only be used for the third-party cookie blocking 347 // policy. It MUST NEVER be used for any kind of SECURITY check. 348 // 349 // For example, if a top-level navigation is redirected, the 350 // first-party for cookies will be the URL of the first URL in the 351 // redirect chain throughout the whole redirect. If it was used for 352 // a security check, an attacker might try to get around this check 353 // by starting from some page that redirects to the 354 // host-to-be-attacked. 355 const GURL& first_party_for_cookies() const { 356 return first_party_for_cookies_; 357 } 358 // This method may be called before Start() or FollowDeferredRedirect() is 359 // called. 360 void set_first_party_for_cookies(const GURL& first_party_for_cookies); 361 362 // The request method, as an uppercase string. "GET" is the default value. 363 // The request method may only be changed before Start() is called and 364 // should only be assigned an uppercase value. 365 const std::string& method() const { return method_; } 366 void set_method(const std::string& method); 367 368 // The referrer URL for the request. This header may actually be suppressed 369 // from the underlying network request for security reasons (e.g., a HTTPS 370 // URL will not be sent as the referrer for a HTTP request). The referrer 371 // may only be changed before Start() is called. 372 const std::string& referrer() const { return referrer_; } 373 // Referrer is sanitized to remove URL fragment, user name and password. 374 void SetReferrer(const std::string& referrer); 375 376 // The referrer policy to apply when updating the referrer during redirects. 377 // The referrer policy may only be changed before Start() is called. 378 void set_referrer_policy(ReferrerPolicy referrer_policy); 379 380 // Sets the delegate of the request. This value may be changed at any time, 381 // and it is permissible for it to be null. 382 void set_delegate(Delegate* delegate); 383 384 // Indicates that the request body should be sent using chunked transfer 385 // encoding. This method may only be called before Start() is called. 386 void EnableChunkedUpload(); 387 388 // Appends the given bytes to the request's upload data to be sent 389 // immediately via chunked transfer encoding. When all data has been sent, 390 // call MarkEndOfChunks() to indicate the end of upload data. 391 // 392 // This method may be called only after calling EnableChunkedUpload(). 393 void AppendChunkToUpload(const char* bytes, 394 int bytes_len, 395 bool is_last_chunk); 396 397 // Sets the upload data. 398 void set_upload(scoped_ptr<UploadDataStream> upload); 399 400 // Gets the upload data. 401 const UploadDataStream* get_upload() const; 402 403 // Returns true if the request has a non-empty message body to upload. 404 bool has_upload() const; 405 406 // Set an extra request header by ID or name, or remove one by name. These 407 // methods may only be called before Start() is called, or before a new 408 // redirect in the request chain. 409 void SetExtraRequestHeaderById(int header_id, const std::string& value, 410 bool overwrite); 411 void SetExtraRequestHeaderByName(const std::string& name, 412 const std::string& value, bool overwrite); 413 void RemoveRequestHeaderByName(const std::string& name); 414 415 // Sets all extra request headers. Any extra request headers set by other 416 // methods are overwritten by this method. This method may only be called 417 // before Start() is called. It is an error to call it later. 418 void SetExtraRequestHeaders(const HttpRequestHeaders& headers); 419 420 const HttpRequestHeaders& extra_request_headers() const { 421 return extra_request_headers_; 422 } 423 424 // Gets the full request headers sent to the server. 425 // 426 // Return true and overwrites headers if it can get the request headers; 427 // otherwise, returns false and does not modify headers. (Always returns 428 // false for request types that don't have headers, like file requests.) 429 // 430 // This is guaranteed to succeed if: 431 // 432 // 1. A redirect or auth callback is currently running. Once it ends, the 433 // headers may become unavailable as a new request with the new address 434 // or credentials is made. 435 // 436 // 2. The OnResponseStarted callback is currently running or has run. 437 bool GetFullRequestHeaders(HttpRequestHeaders* headers) const; 438 439 // Returns the current load state for the request. |param| is an optional 440 // parameter describing details related to the load state. Not all load states 441 // have a parameter. 442 LoadStateWithParam GetLoadState() const; 443 void SetLoadStateParam(const base::string16& param) { 444 load_state_param_ = param; 445 } 446 447 // Returns the current upload progress in bytes. When the upload data is 448 // chunked, size is set to zero, but position will not be. 449 UploadProgress GetUploadProgress() const; 450 451 // Get response header(s) by ID or name. These methods may only be called 452 // once the delegate's OnResponseStarted method has been called. Headers 453 // that appear more than once in the response are coalesced, with values 454 // separated by commas (per RFC 2616). This will not work with cookies since 455 // comma can be used in cookie values. 456 // TODO(darin): add API to enumerate response headers. 457 void GetResponseHeaderById(int header_id, std::string* value); 458 void GetResponseHeaderByName(const std::string& name, std::string* value); 459 460 // Get all response headers, \n-delimited and \n\0-terminated. This includes 461 // the response status line. Restrictions on GetResponseHeaders apply. 462 void GetAllResponseHeaders(std::string* headers); 463 464 // The time when |this| was constructed. 465 base::TimeTicks creation_time() const { return creation_time_; } 466 467 // The time at which the returned response was requested. For cached 468 // responses, this is the last time the cache entry was validated. 469 const base::Time& request_time() const { 470 return response_info_.request_time; 471 } 472 473 // The time at which the returned response was generated. For cached 474 // responses, this is the last time the cache entry was validated. 475 const base::Time& response_time() const { 476 return response_info_.response_time; 477 } 478 479 // Indicate if this response was fetched from disk cache. 480 bool was_cached() const { return response_info_.was_cached; } 481 482 // Returns true if the URLRequest was delivered through a proxy. 483 bool was_fetched_via_proxy() const { 484 return response_info_.was_fetched_via_proxy; 485 } 486 487 // Returns the host and port that the content was fetched from. See 488 // http_response_info.h for caveats relating to cached content. 489 HostPortPair GetSocketAddress() const; 490 491 // Get all response headers, as a HttpResponseHeaders object. See comments 492 // in HttpResponseHeaders class as to the format of the data. 493 HttpResponseHeaders* response_headers() const; 494 495 // Get the SSL connection info. 496 const SSLInfo& ssl_info() const { 497 return response_info_.ssl_info; 498 } 499 500 // Gets timing information related to the request. Events that have not yet 501 // occurred are left uninitialized. After a second request starts, due to 502 // a redirect or authentication, values will be reset. 503 // 504 // LoadTimingInfo only contains ConnectTiming information and socket IDs for 505 // non-cached HTTP responses. 506 void GetLoadTimingInfo(LoadTimingInfo* load_timing_info) const; 507 508 // Returns the cookie values included in the response, if the request is one 509 // that can have cookies. Returns true if the request is a cookie-bearing 510 // type, false otherwise. This method may only be called once the 511 // delegate's OnResponseStarted method has been called. 512 bool GetResponseCookies(ResponseCookies* cookies); 513 514 // Get the mime type. This method may only be called once the delegate's 515 // OnResponseStarted method has been called. 516 void GetMimeType(std::string* mime_type); 517 518 // Get the charset (character encoding). This method may only be called once 519 // the delegate's OnResponseStarted method has been called. 520 void GetCharset(std::string* charset); 521 522 // Returns the HTTP response code (e.g., 200, 404, and so on). This method 523 // may only be called once the delegate's OnResponseStarted method has been 524 // called. For non-HTTP requests, this method returns -1. 525 int GetResponseCode(); 526 527 // Get the HTTP response info in its entirety. 528 const HttpResponseInfo& response_info() const { return response_info_; } 529 530 // Access the LOAD_* flags modifying this request (see load_flags.h). 531 int load_flags() const { return load_flags_; } 532 void set_load_flags(int flags) { load_flags_ = flags; } 533 534 // Returns true if the request is "pending" (i.e., if Start() has been called, 535 // and the response has not yet been called). 536 bool is_pending() const { return is_pending_; } 537 538 // Returns true if the request is in the process of redirecting to a new 539 // URL but has not yet initiated the new request. 540 bool is_redirecting() const { return is_redirecting_; } 541 542 // Returns the error status of the request. 543 const URLRequestStatus& status() const { return status_; } 544 545 // Returns a globally unique identifier for this request. 546 uint64 identifier() const { return identifier_; } 547 548 // This method is called to start the request. The delegate will receive 549 // a OnResponseStarted callback when the request is started. 550 void Start(); 551 552 // This method may be called at any time after Start() has been called to 553 // cancel the request. This method may be called many times, and it has 554 // no effect once the response has completed. It is guaranteed that no 555 // methods of the delegate will be called after the request has been 556 // cancelled, except that this may call the delegate's OnReadCompleted() 557 // during the call to Cancel itself. 558 void Cancel(); 559 560 // Cancels the request and sets the error to |error| (see net_error_list.h 561 // for values). 562 void CancelWithError(int error); 563 564 // Cancels the request and sets the error to |error| (see net_error_list.h 565 // for values) and attaches |ssl_info| as the SSLInfo for that request. This 566 // is useful to attach a certificate and certificate error to a canceled 567 // request. 568 void CancelWithSSLError(int error, const SSLInfo& ssl_info); 569 570 // Read initiates an asynchronous read from the response, and must only 571 // be called after the OnResponseStarted callback is received with a 572 // successful status. 573 // If data is available, Read will return true, and the data and length will 574 // be returned immediately. If data is not available, Read returns false, 575 // and an asynchronous Read is initiated. The Read is finished when 576 // the caller receives the OnReadComplete callback. Unless the request was 577 // cancelled, OnReadComplete will always be called, even if the read failed. 578 // 579 // The buf parameter is a buffer to receive the data. If the operation 580 // completes asynchronously, the implementation will reference the buffer 581 // until OnReadComplete is called. The buffer must be at least max_bytes in 582 // length. 583 // 584 // The max_bytes parameter is the maximum number of bytes to read. 585 // 586 // The bytes_read parameter is an output parameter containing the 587 // the number of bytes read. A value of 0 indicates that there is no 588 // more data available to read from the stream. 589 // 590 // If a read error occurs, Read returns false and the request->status 591 // will be set to an error. 592 bool Read(IOBuffer* buf, int max_bytes, int* bytes_read); 593 594 // If this request is being cached by the HTTP cache, stop subsequent caching. 595 // Note that this method has no effect on other (simultaneous or not) requests 596 // for the same resource. The typical example is a request that results in 597 // the data being stored to disk (downloaded instead of rendered) so we don't 598 // want to store it twice. 599 void StopCaching(); 600 601 // This method may be called to follow a redirect that was deferred in 602 // response to an OnReceivedRedirect call. 603 void FollowDeferredRedirect(); 604 605 // One of the following two methods should be called in response to an 606 // OnAuthRequired() callback (and only then). 607 // SetAuth will reissue the request with the given credentials. 608 // CancelAuth will give up and display the error page. 609 void SetAuth(const AuthCredentials& credentials); 610 void CancelAuth(); 611 612 // This method can be called after the user selects a client certificate to 613 // instruct this URLRequest to continue with the request with the 614 // certificate. Pass NULL if the user doesn't have a client certificate. 615 void ContinueWithCertificate(X509Certificate* client_cert); 616 617 // This method can be called after some error notifications to instruct this 618 // URLRequest to ignore the current error and continue with the request. To 619 // cancel the request instead, call Cancel(). 620 void ContinueDespiteLastError(); 621 622 // Used to specify the context (cookie store, cache) for this request. 623 const URLRequestContext* context() const; 624 625 const BoundNetLog& net_log() const { return net_log_; } 626 627 // Returns the expected content size if available 628 int64 GetExpectedContentSize() const; 629 630 // Returns the priority level for this request. 631 RequestPriority priority() const { return priority_; } 632 633 // Sets the priority level for this request and any related jobs. 634 void SetPriority(RequestPriority priority); 635 636 // Returns true iff this request would be internally redirected to HTTPS 637 // due to HSTS. If so, |redirect_url| is rewritten to the new HTTPS URL. 638 bool GetHSTSRedirect(GURL* redirect_url) const; 639 640 // TODO(willchan): Undo this. Only temporarily public. 641 bool has_delegate() const { return delegate_ != NULL; } 642 643 // NOTE(willchan): This is just temporary for debugging 644 // http://crbug.com/90971. 645 // Allows to setting debug info into the URLRequest. 646 void set_stack_trace(const base::debug::StackTrace& stack_trace); 647 const base::debug::StackTrace* stack_trace() const; 648 649 void set_received_response_content_length(int64 received_content_length) { 650 received_response_content_length_ = received_content_length; 651 } 652 int64 received_response_content_length() { 653 return received_response_content_length_; 654 } 655 656 protected: 657 // Allow the URLRequestJob class to control the is_pending() flag. 658 void set_is_pending(bool value) { is_pending_ = value; } 659 660 // Allow the URLRequestJob class to set our status too 661 void set_status(const URLRequestStatus& value) { status_ = value; } 662 663 // Allow the URLRequestJob to redirect this request. Returns OK if 664 // successful, otherwise an error code is returned. 665 int Redirect(const GURL& location, int http_status_code); 666 667 // Called by URLRequestJob to allow interception when a redirect occurs. 668 void NotifyReceivedRedirect(const GURL& location, bool* defer_redirect); 669 670 // Allow an interceptor's URLRequestJob to restart this request. 671 // Should only be called if the original job has not started a response. 672 void Restart(); 673 674 private: 675 friend class URLRequestJob; 676 677 // Registers a new protocol handler for the given scheme. If the scheme is 678 // already handled, this will overwrite the given factory. To delete the 679 // protocol factory, use NULL for the factory BUT this WILL NOT put back 680 // any previously registered protocol factory. It will have returned 681 // the previously registered factory (or NULL if none is registered) when 682 // the scheme was first registered so that the caller can manually put it 683 // back if desired. 684 // 685 // The scheme must be all-lowercase ASCII. See the ProtocolFactory 686 // declaration for its requirements. 687 // 688 // The registered protocol factory may return NULL, which will cause the 689 // regular "built-in" protocol factory to be used. 690 // 691 static ProtocolFactory* RegisterProtocolFactory(const std::string& scheme, 692 ProtocolFactory* factory); 693 694 // Registers or unregisters a network interception class. 695 static void RegisterRequestInterceptor(Interceptor* interceptor); 696 static void UnregisterRequestInterceptor(Interceptor* interceptor); 697 698 // Resumes or blocks a request paused by the NetworkDelegate::OnBeforeRequest 699 // handler. If |blocked| is true, the request is blocked and an error page is 700 // returned indicating so. This should only be called after Start is called 701 // and OnBeforeRequest returns true (signalling that the request should be 702 // paused). 703 void BeforeRequestComplete(int error); 704 705 void StartJob(URLRequestJob* job); 706 707 // Restarting involves replacing the current job with a new one such as what 708 // happens when following a HTTP redirect. 709 void RestartWithJob(URLRequestJob* job); 710 void PrepareToRestart(); 711 712 // Detaches the job from this request in preparation for this object going 713 // away or the job being replaced. The job will not call us back when it has 714 // been orphaned. 715 void OrphanJob(); 716 717 // Cancels the request and set the error and ssl info for this request to the 718 // passed values. 719 void DoCancel(int error, const SSLInfo& ssl_info); 720 721 // Called by the URLRequestJob when the headers are received, before any other 722 // method, to allow caching of load timing information. 723 void OnHeadersComplete(); 724 725 // Notifies the network delegate that the request has been completed. 726 // This does not imply a successful completion. Also a canceled request is 727 // considered completed. 728 void NotifyRequestCompleted(); 729 730 // Called by URLRequestJob to allow interception when the final response 731 // occurs. 732 void NotifyResponseStarted(); 733 734 // These functions delegate to |delegate_| and may only be used if 735 // |delegate_| is not NULL. See URLRequest::Delegate for the meaning 736 // of these functions. 737 void NotifyAuthRequired(AuthChallengeInfo* auth_info); 738 void NotifyAuthRequiredComplete(NetworkDelegate::AuthRequiredResponse result); 739 void NotifyCertificateRequested(SSLCertRequestInfo* cert_request_info); 740 void NotifySSLCertificateError(const SSLInfo& ssl_info, bool fatal); 741 void NotifyReadCompleted(int bytes_read); 742 743 // These functions delegate to |network_delegate_| if it is not NULL. 744 // If |network_delegate_| is NULL, cookies can be used unless 745 // SetDefaultCookiePolicyToBlock() has been called. 746 bool CanGetCookies(const CookieList& cookie_list) const; 747 bool CanSetCookie(const std::string& cookie_line, 748 CookieOptions* options) const; 749 bool CanEnablePrivacyMode() const; 750 751 // Called when the delegate blocks or unblocks this request when intercepting 752 // certain requests. 753 void SetBlockedOnDelegate(); 754 void SetUnblockedOnDelegate(); 755 756 // Contextual information used for this request. Cannot be NULL. This contains 757 // most of the dependencies which are shared between requests (disk cache, 758 // cookie store, socket pool, etc.) 759 const URLRequestContext* context_; 760 761 NetworkDelegate* network_delegate_; 762 763 // Tracks the time spent in various load states throughout this request. 764 BoundNetLog net_log_; 765 766 scoped_refptr<URLRequestJob> job_; 767 scoped_ptr<UploadDataStream> upload_data_stream_; 768 std::vector<GURL> url_chain_; 769 GURL first_party_for_cookies_; 770 GURL delegate_redirect_url_; 771 std::string method_; // "GET", "POST", etc. Should be all uppercase. 772 std::string referrer_; 773 ReferrerPolicy referrer_policy_; 774 HttpRequestHeaders extra_request_headers_; 775 int load_flags_; // Flags indicating the request type for the load; 776 // expected values are LOAD_* enums above. 777 778 // Never access methods of the |delegate_| directly. Always use the 779 // Notify... methods for this. 780 Delegate* delegate_; 781 782 // Current error status of the job. When no error has been encountered, this 783 // will be SUCCESS. If multiple errors have been encountered, this will be 784 // the first non-SUCCESS status seen. 785 URLRequestStatus status_; 786 787 // The HTTP response info, lazily initialized. 788 HttpResponseInfo response_info_; 789 790 // Tells us whether the job is outstanding. This is true from the time 791 // Start() is called to the time we dispatch RequestComplete and indicates 792 // whether the job is active. 793 bool is_pending_; 794 795 // Indicates if the request is in the process of redirecting to a new 796 // location. It is true from the time the headers complete until a 797 // new request begins. 798 bool is_redirecting_; 799 800 // Number of times we're willing to redirect. Used to guard against 801 // infinite redirects. 802 int redirect_limit_; 803 804 // Cached value for use after we've orphaned the job handling the 805 // first transaction in a request involving redirects. 806 UploadProgress final_upload_progress_; 807 808 // The priority level for this request. Objects like ClientSocketPool use 809 // this to determine which URLRequest to allocate sockets to first. 810 RequestPriority priority_; 811 812 // TODO(battre): The only consumer of the identifier_ is currently the 813 // web request API. We need to match identifiers of requests between the 814 // web request API and the web navigation API. As the URLRequest does not 815 // exist when the web navigation API is triggered, the tracking probably 816 // needs to be done outside of the URLRequest anyway. Therefore, this 817 // identifier should be deleted here. http://crbug.com/89321 818 // A globally unique identifier for this request. 819 const uint64 identifier_; 820 821 // True if this request is blocked waiting for the network delegate to resume 822 // it. 823 bool blocked_on_delegate_; 824 825 // An optional parameter that provides additional information about the load 826 // state. Only used with the LOAD_STATE_WAITING_FOR_DELEGATE state. 827 base::string16 load_state_param_; 828 829 base::debug::LeakTracker<URLRequest> leak_tracker_; 830 831 // Callback passed to the network delegate to notify us when a blocked request 832 // is ready to be resumed or canceled. 833 CompletionCallback before_request_callback_; 834 835 // Safe-guard to ensure that we do not send multiple "I am completed" 836 // messages to network delegate. 837 // TODO(battre): Remove this. http://crbug.com/89049 838 bool has_notified_completion_; 839 840 // Authentication data used by the NetworkDelegate for this request, 841 // if one is present. |auth_credentials_| may be filled in when calling 842 // |NotifyAuthRequired| on the NetworkDelegate. |auth_info_| holds 843 // the authentication challenge being handled by |NotifyAuthRequired|. 844 AuthCredentials auth_credentials_; 845 scoped_refptr<AuthChallengeInfo> auth_info_; 846 847 int64 received_response_content_length_; 848 849 base::TimeTicks creation_time_; 850 851 // Timing information for the most recent request. Its start times are 852 // populated during Start(), and the rest are populated in OnResponseReceived. 853 LoadTimingInfo load_timing_info_; 854 855 scoped_ptr<const base::debug::StackTrace> stack_trace_; 856 857 DISALLOW_COPY_AND_ASSIGN(URLRequest); 858}; 859 860} // namespace net 861 862#endif // NET_URL_REQUEST_URL_REQUEST_H_ 863