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