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