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