url_request.h revision 90dce4d38c5ff5333bea97d859d4e484e27edf0c
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/string16.h" 15#include "base/supports_user_data.h" 16#include "base/time.h" 17#include "base/threading/non_thread_safe.h" 18#include "googleurl/src/gurl.h" 19#include "net/base/auth.h" 20#include "net/base/completion_callback.h" 21#include "net/base/load_states.h" 22#include "net/base/load_timing_info.h" 23#include "net/base/net_export.h" 24#include "net/base/net_log.h" 25#include "net/base/network_delegate.h" 26#include "net/base/request_priority.h" 27#include "net/base/upload_progress.h" 28#include "net/cookies/canonical_cookie.h" 29#include "net/http/http_request_headers.h" 30#include "net/http/http_response_info.h" 31#include "net/url_request/url_request_status.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 // Returns the current load state for the request. |param| is an optional 425 // parameter describing details related to the load state. Not all load states 426 // have a parameter. 427 LoadStateWithParam GetLoadState() const; 428 void SetLoadStateParam(const base::string16& param) { 429 load_state_param_ = param; 430 } 431 432 // Returns the current upload progress in bytes. When the upload data is 433 // chunked, size is set to zero, but position will not be. 434 UploadProgress GetUploadProgress() const; 435 436 // Get response header(s) by ID or name. These methods may only be called 437 // once the delegate's OnResponseStarted method has been called. Headers 438 // that appear more than once in the response are coalesced, with values 439 // separated by commas (per RFC 2616). This will not work with cookies since 440 // comma can be used in cookie values. 441 // TODO(darin): add API to enumerate response headers. 442 void GetResponseHeaderById(int header_id, std::string* value); 443 void GetResponseHeaderByName(const std::string& name, std::string* value); 444 445 // Get all response headers, \n-delimited and \n\0-terminated. This includes 446 // the response status line. Restrictions on GetResponseHeaders apply. 447 void GetAllResponseHeaders(std::string* headers); 448 449 // The time when |this| was constructed. 450 base::TimeTicks creation_time() const { return creation_time_; } 451 452 // The time at which the returned response was requested. For cached 453 // responses, this is the last time the cache entry was validated. 454 const base::Time& request_time() const { 455 return response_info_.request_time; 456 } 457 458 // The time at which the returned response was generated. For cached 459 // responses, this is the last time the cache entry was validated. 460 const base::Time& response_time() const { 461 return response_info_.response_time; 462 } 463 464 // Indicate if this response was fetched from disk cache. 465 bool was_cached() const { return response_info_.was_cached; } 466 467 // Returns true if the URLRequest was delivered through a proxy. 468 bool was_fetched_via_proxy() const { 469 return response_info_.was_fetched_via_proxy; 470 } 471 472 // Returns the host and port that the content was fetched from. See 473 // http_response_info.h for caveats relating to cached content. 474 HostPortPair GetSocketAddress() const; 475 476 // Get all response headers, as a HttpResponseHeaders object. See comments 477 // in HttpResponseHeaders class as to the format of the data. 478 HttpResponseHeaders* response_headers() const; 479 480 // Get the SSL connection info. 481 const SSLInfo& ssl_info() const { 482 return response_info_.ssl_info; 483 } 484 485 // Gets timing information related to the request. Events that have not yet 486 // occurred are left uninitialized. After a second request starts, due to 487 // a redirect or authentication, values will be reset. 488 // 489 // LoadTimingInfo only contains ConnectTiming information and socket IDs for 490 // non-cached HTTP responses. 491 void GetLoadTimingInfo(LoadTimingInfo* load_timing_info) const; 492 493 // Returns the cookie values included in the response, if the request is one 494 // that can have cookies. Returns true if the request is a cookie-bearing 495 // type, false otherwise. This method may only be called once the 496 // delegate's OnResponseStarted method has been called. 497 bool GetResponseCookies(ResponseCookies* cookies); 498 499 // Get the mime type. This method may only be called once the delegate's 500 // OnResponseStarted method has been called. 501 void GetMimeType(std::string* mime_type); 502 503 // Get the charset (character encoding). This method may only be called once 504 // the delegate's OnResponseStarted method has been called. 505 void GetCharset(std::string* charset); 506 507 // Returns the HTTP response code (e.g., 200, 404, and so on). This method 508 // may only be called once the delegate's OnResponseStarted method has been 509 // called. For non-HTTP requests, this method returns -1. 510 int GetResponseCode(); 511 512 // Get the HTTP response info in its entirety. 513 const HttpResponseInfo& response_info() const { return response_info_; } 514 515 // Access the LOAD_* flags modifying this request (see load_flags.h). 516 int load_flags() const { return load_flags_; } 517 void set_load_flags(int flags) { load_flags_ = flags; } 518 519 // Returns true if the request is "pending" (i.e., if Start() has been called, 520 // and the response has not yet been called). 521 bool is_pending() const { return is_pending_; } 522 523 // Returns true if the request is in the process of redirecting to a new 524 // URL but has not yet initiated the new request. 525 bool is_redirecting() const { return is_redirecting_; } 526 527 // Returns the error status of the request. 528 const URLRequestStatus& status() const { return status_; } 529 530 // Returns a globally unique identifier for this request. 531 uint64 identifier() const { return identifier_; } 532 533 // This method is called to start the request. The delegate will receive 534 // a OnResponseStarted callback when the request is started. 535 void Start(); 536 537 // This method may be called at any time after Start() has been called to 538 // cancel the request. This method may be called many times, and it has 539 // no effect once the response has completed. It is guaranteed that no 540 // methods of the delegate will be called after the request has been 541 // cancelled, except that this may call the delegate's OnReadCompleted() 542 // during the call to Cancel itself. 543 void Cancel(); 544 545 // Cancels the request and sets the error to |error| (see net_error_list.h 546 // for values). 547 void CancelWithError(int error); 548 549 // Cancels the request and sets the error to |error| (see net_error_list.h 550 // for values) and attaches |ssl_info| as the SSLInfo for that request. This 551 // is useful to attach a certificate and certificate error to a canceled 552 // request. 553 void CancelWithSSLError(int error, const SSLInfo& ssl_info); 554 555 // Read initiates an asynchronous read from the response, and must only 556 // be called after the OnResponseStarted callback is received with a 557 // successful status. 558 // If data is available, Read will return true, and the data and length will 559 // be returned immediately. If data is not available, Read returns false, 560 // and an asynchronous Read is initiated. The Read is finished when 561 // the caller receives the OnReadComplete callback. Unless the request was 562 // cancelled, OnReadComplete will always be called, even if the read failed. 563 // 564 // The buf parameter is a buffer to receive the data. If the operation 565 // completes asynchronously, the implementation will reference the buffer 566 // until OnReadComplete is called. The buffer must be at least max_bytes in 567 // length. 568 // 569 // The max_bytes parameter is the maximum number of bytes to read. 570 // 571 // The bytes_read parameter is an output parameter containing the 572 // the number of bytes read. A value of 0 indicates that there is no 573 // more data available to read from the stream. 574 // 575 // If a read error occurs, Read returns false and the request->status 576 // will be set to an error. 577 bool Read(IOBuffer* buf, int max_bytes, int* bytes_read); 578 579 // If this request is being cached by the HTTP cache, stop subsequent caching. 580 // Note that this method has no effect on other (simultaneous or not) requests 581 // for the same resource. The typical example is a request that results in 582 // the data being stored to disk (downloaded instead of rendered) so we don't 583 // want to store it twice. 584 void StopCaching(); 585 586 // This method may be called to follow a redirect that was deferred in 587 // response to an OnReceivedRedirect call. 588 void FollowDeferredRedirect(); 589 590 // One of the following two methods should be called in response to an 591 // OnAuthRequired() callback (and only then). 592 // SetAuth will reissue the request with the given credentials. 593 // CancelAuth will give up and display the error page. 594 void SetAuth(const AuthCredentials& credentials); 595 void CancelAuth(); 596 597 // This method can be called after the user selects a client certificate to 598 // instruct this URLRequest to continue with the request with the 599 // certificate. Pass NULL if the user doesn't have a client certificate. 600 void ContinueWithCertificate(X509Certificate* client_cert); 601 602 // This method can be called after some error notifications to instruct this 603 // URLRequest to ignore the current error and continue with the request. To 604 // cancel the request instead, call Cancel(). 605 void ContinueDespiteLastError(); 606 607 // Used to specify the context (cookie store, cache) for this request. 608 const URLRequestContext* context() const; 609 610 const BoundNetLog& net_log() const { return net_log_; } 611 612 // Returns the expected content size if available 613 int64 GetExpectedContentSize() const; 614 615 // Returns the priority level for this request. 616 RequestPriority priority() const { return priority_; } 617 618 // Sets the priority level for this request and any related jobs. 619 void SetPriority(RequestPriority priority); 620 621 // Returns true iff this request would be internally redirected to HTTPS 622 // due to HSTS. If so, |redirect_url| is rewritten to the new HTTPS URL. 623 bool GetHSTSRedirect(GURL* redirect_url) const; 624 625 // TODO(willchan): Undo this. Only temporarily public. 626 bool has_delegate() const { return delegate_ != NULL; } 627 628 // NOTE(willchan): This is just temporary for debugging 629 // http://crbug.com/90971. 630 // Allows to setting debug info into the URLRequest. 631 void set_stack_trace(const base::debug::StackTrace& stack_trace); 632 const base::debug::StackTrace* stack_trace() const; 633 634 void set_received_response_content_length(int64 received_content_length) { 635 received_response_content_length_ = received_content_length; 636 } 637 int64 received_response_content_length() { 638 return received_response_content_length_; 639 } 640 641 protected: 642 // Allow the URLRequestJob class to control the is_pending() flag. 643 void set_is_pending(bool value) { is_pending_ = value; } 644 645 // Allow the URLRequestJob class to set our status too 646 void set_status(const URLRequestStatus& value) { status_ = value; } 647 648 // Allow the URLRequestJob to redirect this request. Returns OK if 649 // successful, otherwise an error code is returned. 650 int Redirect(const GURL& location, int http_status_code); 651 652 // Called by URLRequestJob to allow interception when a redirect occurs. 653 void NotifyReceivedRedirect(const GURL& location, bool* defer_redirect); 654 655 // Allow an interceptor's URLRequestJob to restart this request. 656 // Should only be called if the original job has not started a response. 657 void Restart(); 658 659 private: 660 friend class URLRequestJob; 661 662 // Registers a new protocol handler for the given scheme. If the scheme is 663 // already handled, this will overwrite the given factory. To delete the 664 // protocol factory, use NULL for the factory BUT this WILL NOT put back 665 // any previously registered protocol factory. It will have returned 666 // the previously registered factory (or NULL if none is registered) when 667 // the scheme was first registered so that the caller can manually put it 668 // back if desired. 669 // 670 // The scheme must be all-lowercase ASCII. See the ProtocolFactory 671 // declaration for its requirements. 672 // 673 // The registered protocol factory may return NULL, which will cause the 674 // regular "built-in" protocol factory to be used. 675 // 676 static ProtocolFactory* RegisterProtocolFactory(const std::string& scheme, 677 ProtocolFactory* factory); 678 679 // Registers or unregisters a network interception class. 680 static void RegisterRequestInterceptor(Interceptor* interceptor); 681 static void UnregisterRequestInterceptor(Interceptor* interceptor); 682 683 // Resumes or blocks a request paused by the NetworkDelegate::OnBeforeRequest 684 // handler. If |blocked| is true, the request is blocked and an error page is 685 // returned indicating so. This should only be called after Start is called 686 // and OnBeforeRequest returns true (signalling that the request should be 687 // paused). 688 void BeforeRequestComplete(int error); 689 690 void StartJob(URLRequestJob* job); 691 692 // Restarting involves replacing the current job with a new one such as what 693 // happens when following a HTTP redirect. 694 void RestartWithJob(URLRequestJob* job); 695 void PrepareToRestart(); 696 697 // Detaches the job from this request in preparation for this object going 698 // away or the job being replaced. The job will not call us back when it has 699 // been orphaned. 700 void OrphanJob(); 701 702 // Cancels the request and set the error and ssl info for this request to the 703 // passed values. 704 void DoCancel(int error, const SSLInfo& ssl_info); 705 706 // Called by the URLRequestJob when the headers are received, before any other 707 // method, to allow caching of load timing information. 708 void OnHeadersComplete(); 709 710 // Notifies the network delegate that the request has been completed. 711 // This does not imply a successful completion. Also a canceled request is 712 // considered completed. 713 void NotifyRequestCompleted(); 714 715 // Called by URLRequestJob to allow interception when the final response 716 // occurs. 717 void NotifyResponseStarted(); 718 719 // These functions delegate to |delegate_| and may only be used if 720 // |delegate_| is not NULL. See URLRequest::Delegate for the meaning 721 // of these functions. 722 void NotifyAuthRequired(AuthChallengeInfo* auth_info); 723 void NotifyAuthRequiredComplete(NetworkDelegate::AuthRequiredResponse result); 724 void NotifyCertificateRequested(SSLCertRequestInfo* cert_request_info); 725 void NotifySSLCertificateError(const SSLInfo& ssl_info, bool fatal); 726 void NotifyReadCompleted(int bytes_read); 727 728 // These functions delegate to |network_delegate_| if it is not NULL. 729 // If |network_delegate_| is NULL, cookies can be used unless 730 // SetDefaultCookiePolicyToBlock() has been called. 731 bool CanGetCookies(const CookieList& cookie_list) const; 732 bool CanSetCookie(const std::string& cookie_line, 733 CookieOptions* options) const; 734 bool CanEnablePrivacyMode() const; 735 736 // Called when the delegate blocks or unblocks this request when intercepting 737 // certain requests. 738 void SetBlockedOnDelegate(); 739 void SetUnblockedOnDelegate(); 740 741 // Contextual information used for this request. Cannot be NULL. This contains 742 // most of the dependencies which are shared between requests (disk cache, 743 // cookie store, socket pool, etc.) 744 const URLRequestContext* context_; 745 746 NetworkDelegate* network_delegate_; 747 748 // Tracks the time spent in various load states throughout this request. 749 BoundNetLog net_log_; 750 751 scoped_refptr<URLRequestJob> job_; 752 scoped_ptr<UploadDataStream> upload_data_stream_; 753 std::vector<GURL> url_chain_; 754 GURL first_party_for_cookies_; 755 GURL delegate_redirect_url_; 756 std::string method_; // "GET", "POST", etc. Should be all uppercase. 757 std::string referrer_; 758 ReferrerPolicy referrer_policy_; 759 HttpRequestHeaders extra_request_headers_; 760 int load_flags_; // Flags indicating the request type for the load; 761 // expected values are LOAD_* enums above. 762 763 // Never access methods of the |delegate_| directly. Always use the 764 // Notify... methods for this. 765 Delegate* delegate_; 766 767 // Current error status of the job. When no error has been encountered, this 768 // will be SUCCESS. If multiple errors have been encountered, this will be 769 // the first non-SUCCESS status seen. 770 URLRequestStatus status_; 771 772 // The HTTP response info, lazily initialized. 773 HttpResponseInfo response_info_; 774 775 // Tells us whether the job is outstanding. This is true from the time 776 // Start() is called to the time we dispatch RequestComplete and indicates 777 // whether the job is active. 778 bool is_pending_; 779 780 // Indicates if the request is in the process of redirecting to a new 781 // location. It is true from the time the headers complete until a 782 // new request begins. 783 bool is_redirecting_; 784 785 // Number of times we're willing to redirect. Used to guard against 786 // infinite redirects. 787 int redirect_limit_; 788 789 // Cached value for use after we've orphaned the job handling the 790 // first transaction in a request involving redirects. 791 UploadProgress final_upload_progress_; 792 793 // The priority level for this request. Objects like ClientSocketPool use 794 // this to determine which URLRequest to allocate sockets to first. 795 RequestPriority priority_; 796 797 // TODO(battre): The only consumer of the identifier_ is currently the 798 // web request API. We need to match identifiers of requests between the 799 // web request API and the web navigation API. As the URLRequest does not 800 // exist when the web navigation API is triggered, the tracking probably 801 // needs to be done outside of the URLRequest anyway. Therefore, this 802 // identifier should be deleted here. http://crbug.com/89321 803 // A globally unique identifier for this request. 804 const uint64 identifier_; 805 806 // True if this request is blocked waiting for the network delegate to resume 807 // it. 808 bool blocked_on_delegate_; 809 810 // An optional parameter that provides additional information about the load 811 // state. Only used with the LOAD_STATE_WAITING_FOR_DELEGATE state. 812 base::string16 load_state_param_; 813 814 base::debug::LeakTracker<URLRequest> leak_tracker_; 815 816 // Callback passed to the network delegate to notify us when a blocked request 817 // is ready to be resumed or canceled. 818 CompletionCallback before_request_callback_; 819 820 // Safe-guard to ensure that we do not send multiple "I am completed" 821 // messages to network delegate. 822 // TODO(battre): Remove this. http://crbug.com/89049 823 bool has_notified_completion_; 824 825 // Authentication data used by the NetworkDelegate for this request, 826 // if one is present. |auth_credentials_| may be filled in when calling 827 // |NotifyAuthRequired| on the NetworkDelegate. |auth_info_| holds 828 // the authentication challenge being handled by |NotifyAuthRequired|. 829 AuthCredentials auth_credentials_; 830 scoped_refptr<AuthChallengeInfo> auth_info_; 831 832 int64 received_response_content_length_; 833 834 base::TimeTicks creation_time_; 835 836 // Timing information for the most recent request. Its start times are 837 // populated during Start(), and the rest are populated in OnResponseReceived. 838 LoadTimingInfo load_timing_info_; 839 840 scoped_ptr<const base::debug::StackTrace> stack_trace_; 841 842 DISALLOW_COPY_AND_ASSIGN(URLRequest); 843}; 844 845} // namespace net 846 847#endif // NET_URL_REQUEST_URL_REQUEST_H_ 848