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/memory/scoped_ptr.h"
15 #include "base/strings/string16.h"
16 #include "base/supports_user_data.h"
17 #include "base/threading/non_thread_safe.h"
18 #include "base/time/time.h"
19 #include "net/base/auth.h"
20 #include "net/base/completion_callback.h"
21 #include "net/base/load_states.h"
22 #include "net/base/load_timing_info.h"
23 #include "net/base/net_export.h"
24 #include "net/base/net_log.h"
25 #include "net/base/network_delegate.h"
26 #include "net/base/request_priority.h"
27 #include "net/base/upload_progress.h"
28 #include "net/cookies/canonical_cookie.h"
29 #include "net/cookies/cookie_store.h"
30 #include "net/http/http_request_headers.h"
31 #include "net/http/http_response_info.h"
32 #include "net/url_request/url_request_status.h"
43 // Temporary layering violation to allow existing users of a deprecated
46 class AppCacheInterceptor;
51 class ChunkedUploadDataStream;
55 struct LoadTimingInfo;
57 class SSLCertRequestInfo;
59 class UploadDataStream;
60 class URLRequestContext;
62 class X509Certificate;
64 // This stores the values of the Set-Cookie headers received during the request.
65 // Each item in the vector corresponds to a Set-Cookie: line received,
66 // excluding the "Set-Cookie:" part.
67 typedef std::vector<std::string> ResponseCookies;
69 //-----------------------------------------------------------------------------
70 // A class representing the asynchronous load of a data stream from an URL.
72 // The lifetime of an instance of this class is completely controlled by the
73 // consumer, and the instance is not required to live on the heap or be
74 // allocated in any special way. It is also valid to delete an URLRequest
75 // object during the handling of a callback to its delegate. Of course, once
76 // the URLRequest is deleted, no further callbacks to its delegate will occur.
78 // NOTE: All usage of all instances of this class should be on the same thread.
80 class NET_EXPORT URLRequest : NON_EXPORTED_BASE(public base::NonThreadSafe),
81 public base::SupportsUserData {
83 // Callback function implemented by protocol handlers to create new jobs.
84 // The factory may return NULL to indicate an error, which will cause other
85 // factories to be queried. If no factory handles the request, then the
86 // default job will be used.
87 typedef URLRequestJob* (ProtocolFactory)(URLRequest* request,
88 NetworkDelegate* network_delegate,
89 const std::string& scheme);
91 // HTTP request/response header IDs (via some preprocessor fun) for use with
92 // SetRequestHeaderById and GetResponseHeaderById.
94 #define HTTP_ATOM(x) HTTP_ ## x,
95 #include "net/http/http_atom_list.h"
99 // Referrer policies (see set_referrer_policy): During server redirects, the
100 // referrer header might be cleared, if the protocol changes from HTTPS to
101 // HTTP. This is the default behavior of URLRequest, corresponding to
102 // CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE. Alternatively, the
103 // referrer policy can be set to never change the referrer header. This
104 // behavior corresponds to NEVER_CLEAR_REFERRER. Embedders will want to use
105 // NEVER_CLEAR_REFERRER when implementing the meta-referrer support
106 // (http://wiki.whatwg.org/wiki/Meta_referrer) and sending requests with a
107 // non-default referrer policy. Only the default referrer policy requires
108 // the referrer to be cleared on transitions from HTTPS to HTTP.
109 enum ReferrerPolicy {
110 CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
111 NEVER_CLEAR_REFERRER,
114 // First-party URL redirect policy: During server redirects, the first-party
115 // URL for cookies normally doesn't change. However, if the request is a
116 // top-level first-party request, the first-party URL should be updated to the
117 // URL on every redirect.
118 enum FirstPartyURLPolicy {
119 NEVER_CHANGE_FIRST_PARTY_URL,
120 UPDATE_FIRST_PARTY_URL_ON_REDIRECT,
123 // This class handles network interception. Use with
124 // (Un)RegisterRequestInterceptor.
125 class NET_EXPORT Interceptor {
127 virtual ~Interceptor() {}
129 // Called for every request made. Should return a new job to handle the
130 // request if it should be intercepted, or NULL to allow the request to
131 // be handled in the normal manner.
132 virtual URLRequestJob* MaybeIntercept(
133 URLRequest* request, NetworkDelegate* network_delegate) = 0;
135 // Called after having received a redirect response, but prior to the
136 // the request delegate being informed of the redirect. Can return a new
137 // job to replace the existing job if it should be intercepted, or NULL
138 // to allow the normal handling to continue. If a new job is provided,
139 // the delegate never sees the original redirect response, instead the
140 // response produced by the intercept job will be returned.
141 virtual URLRequestJob* MaybeInterceptRedirect(
143 NetworkDelegate* network_delegate,
144 const GURL& location);
146 // Called after having received a final response, but prior to the
147 // the request delegate being informed of the response. This is also
148 // called when there is no server response at all to allow interception
149 // on dns or network errors. Can return a new job to replace the existing
150 // job if it should be intercepted, or NULL to allow the normal handling to
151 // continue. If a new job is provided, the delegate never sees the original
152 // response, instead the response produced by the intercept job will be
154 virtual URLRequestJob* MaybeInterceptResponse(
155 URLRequest* request, NetworkDelegate* network_delegate);
158 // Deprecated interfaces in net::URLRequest. They have been moved to
159 // URLRequest's private section to prevent new uses. Existing uses are
160 // explicitly friended here and should be removed over time.
161 class NET_EXPORT Deprecated {
163 // TODO(willchan): Kill off these friend declarations.
164 friend class TestInterceptor;
165 friend class content::AppCacheInterceptor;
167 // TODO(pauljensen): Remove this when AppCacheInterceptor is a
168 // ProtocolHandler, see crbug.com/161547.
169 static void RegisterRequestInterceptor(Interceptor* interceptor);
170 static void UnregisterRequestInterceptor(Interceptor* interceptor);
172 DISALLOW_IMPLICIT_CONSTRUCTORS(Deprecated);
175 // The delegate's methods are called from the message loop of the thread
176 // on which the request's Start() method is called. See above for the
177 // ordering of callbacks.
179 // The callbacks will be called in the following order:
181 // - OnCertificateRequested* (zero or more calls, if the SSL server and/or
182 // SSL proxy requests a client certificate for authentication)
183 // - OnSSLCertificateError* (zero or one call, if the SSL server's
184 // certificate has an error)
185 // - OnReceivedRedirect* (zero or more calls, for the number of redirects)
186 // - OnAuthRequired* (zero or more calls, for the number of
187 // authentication failures)
188 // - OnResponseStarted
189 // Read() initiated by delegate
190 // - OnReadCompleted* (zero or more calls until all data is read)
192 // Read() must be called at least once. Read() returns true when it completed
193 // immediately, and false if an IO is pending or if there is an error. When
194 // Read() returns false, the caller can check the Request's status() to see
195 // if an error occurred, or if the IO is just pending. When Read() returns
196 // true with zero bytes read, it indicates the end of the response.
198 class NET_EXPORT Delegate {
200 // Called upon receiving a redirect. The delegate may call the request's
201 // Cancel method to prevent the redirect from being followed. Since there
202 // may be multiple chained redirects, there may also be more than one
205 // When this function is called, the request will still contain the
206 // original URL, the destination of the redirect is provided in 'new_url'.
207 // If the delegate does not cancel the request and |*defer_redirect| is
208 // false, then the redirect will be followed, and the request's URL will be
209 // changed to the new URL. Otherwise if the delegate does not cancel the
210 // request and |*defer_redirect| is true, then the redirect will be
211 // followed once FollowDeferredRedirect is called on the URLRequest.
213 // The caller must set |*defer_redirect| to false, so that delegates do not
214 // need to set it if they are happy with the default behavior of not
215 // deferring redirect.
216 virtual void OnReceivedRedirect(URLRequest* request,
217 const RedirectInfo& redirect_info,
218 bool* defer_redirect);
220 // Called when we receive an authentication failure. The delegate should
221 // call request->SetAuth() with the user's credentials once it obtains them,
222 // or request->CancelAuth() to cancel the login and display the error page.
223 // When it does so, the request will be reissued, restarting the sequence
225 virtual void OnAuthRequired(URLRequest* request,
226 AuthChallengeInfo* auth_info);
228 // Called when we receive an SSL CertificateRequest message for client
229 // authentication. The delegate should call
230 // request->ContinueWithCertificate() with the client certificate the user
231 // selected, or request->ContinueWithCertificate(NULL) to continue the SSL
232 // handshake without a client certificate.
233 virtual void OnCertificateRequested(
235 SSLCertRequestInfo* cert_request_info);
237 // Called when using SSL and the server responds with a certificate with
238 // an error, for example, whose common name does not match the common name
239 // we were expecting for that host. The delegate should either do the
240 // safe thing and Cancel() the request or decide to proceed by calling
241 // ContinueDespiteLastError(). cert_error is a ERR_* error code
242 // indicating what's wrong with the certificate.
243 // If |fatal| is true then the host in question demands a higher level
244 // of security (due e.g. to HTTP Strict Transport Security, user
245 // preference, or built-in policy). In this case, errors must not be
246 // bypassable by the user.
247 virtual void OnSSLCertificateError(URLRequest* request,
248 const SSLInfo& ssl_info,
251 // Called to notify that the request must use the network to complete the
252 // request and is about to do so. This is called at most once per
253 // URLRequest, and by default does not defer. If deferred, call
254 // ResumeNetworkStart() to continue or Cancel() to cancel.
255 virtual void OnBeforeNetworkStart(URLRequest* request, bool* defer);
257 // After calling Start(), the delegate will receive an OnResponseStarted
258 // callback when the request has completed. If an error occurred, the
259 // request->status() will be set. On success, all redirects have been
260 // followed and the final response is beginning to arrive. At this point,
261 // meta data about the response is available, including for example HTTP
262 // response headers if this is a request for a HTTP resource.
263 virtual void OnResponseStarted(URLRequest* request) = 0;
265 // Called when the a Read of the response body is completed after an
266 // IO_PENDING status from a Read() call.
267 // The data read is filled into the buffer which the caller passed
268 // to Read() previously.
270 // If an error occurred, request->status() will contain the error,
271 // and bytes read will be -1.
272 virtual void OnReadCompleted(URLRequest* request, int bytes_read) = 0;
275 virtual ~Delegate() {}
278 // If destroyed after Start() has been called but while IO is pending,
279 // then the request will be effectively canceled and the delegate
280 // will not have any more of its methods called.
281 ~URLRequest() override;
283 // Changes the default cookie policy from allowing all cookies to blocking all
284 // cookies. Embedders that want to implement a more flexible policy should
285 // change the default to blocking all cookies, and provide a NetworkDelegate
286 // with the URLRequestContext that maintains the CookieStore.
287 // The cookie policy default has to be set before the first URLRequest is
288 // started. Once it was set to block all cookies, it cannot be changed back.
289 static void SetDefaultCookiePolicyToBlock();
291 // Returns true if the scheme can be handled by URLRequest. False otherwise.
292 static bool IsHandledProtocol(const std::string& scheme);
294 // Returns true if the url can be handled by URLRequest. False otherwise.
295 // The function returns true for invalid urls because URLRequest knows how
297 // NOTE: This will also return true for URLs that are handled by
298 // ProtocolFactories that only work for requests that are scoped to a
300 static bool IsHandledURL(const GURL& url);
302 // The original url is the url used to initialize the request, and it may
303 // differ from the url if the request was redirected.
304 const GURL& original_url() const { return url_chain_.front(); }
305 // The chain of urls traversed by this request. If the request had no
306 // redirects, this vector will contain one element.
307 const std::vector<GURL>& url_chain() const { return url_chain_; }
308 const GURL& url() const { return url_chain_.back(); }
310 // The URL that should be consulted for the third-party cookie blocking
313 // WARNING: This URL must only be used for the third-party cookie blocking
314 // policy. It MUST NEVER be used for any kind of SECURITY check.
316 // For example, if a top-level navigation is redirected, the
317 // first-party for cookies will be the URL of the first URL in the
318 // redirect chain throughout the whole redirect. If it was used for
319 // a security check, an attacker might try to get around this check
320 // by starting from some page that redirects to the
321 // host-to-be-attacked.
322 const GURL& first_party_for_cookies() const {
323 return first_party_for_cookies_;
325 // This method may only be called before Start().
326 void set_first_party_for_cookies(const GURL& first_party_for_cookies);
328 // The first-party URL policy to apply when updating the first party URL
329 // during redirects. The first-party URL policy may only be changed before
330 // Start() is called.
331 FirstPartyURLPolicy first_party_url_policy() const {
332 return first_party_url_policy_;
334 void set_first_party_url_policy(FirstPartyURLPolicy first_party_url_policy);
336 // The request method, as an uppercase string. "GET" is the default value.
337 // The request method may only be changed before Start() is called and
338 // should only be assigned an uppercase value.
339 const std::string& method() const { return method_; }
340 void set_method(const std::string& method);
342 // Determines the new method of the request afer following a redirect.
343 // |method| is the method used to arrive at the redirect,
344 // |http_status_code| is the status code associated with the redirect.
345 static std::string ComputeMethodForRedirect(const std::string& method,
346 int http_status_code);
348 // The referrer URL for the request. This header may actually be suppressed
349 // from the underlying network request for security reasons (e.g., a HTTPS
350 // URL will not be sent as the referrer for a HTTP request). The referrer
351 // may only be changed before Start() is called.
352 const std::string& referrer() const { return referrer_; }
353 // Referrer is sanitized to remove URL fragment, user name and password.
354 void SetReferrer(const std::string& referrer);
356 // The referrer policy to apply when updating the referrer during redirects.
357 // The referrer policy may only be changed before Start() is called.
358 ReferrerPolicy referrer_policy() const { return referrer_policy_; }
359 void set_referrer_policy(ReferrerPolicy referrer_policy);
361 // Sets the delegate of the request. This value may be changed at any time,
362 // and it is permissible for it to be null.
363 void set_delegate(Delegate* delegate);
365 // Indicates that the request body should be sent using chunked transfer
366 // encoding. This method may only be called before Start() is called.
367 void EnableChunkedUpload();
369 // Appends the given bytes to the request's upload data to be sent
370 // immediately via chunked transfer encoding. When all data has been sent,
371 // call MarkEndOfChunks() to indicate the end of upload data.
373 // This method may be called only after calling EnableChunkedUpload().
374 void AppendChunkToUpload(const char* bytes,
378 // Sets the upload data.
379 void set_upload(scoped_ptr<UploadDataStream> upload);
381 // Gets the upload data.
382 const UploadDataStream* get_upload() const;
384 // Returns true if the request has a non-empty message body to upload.
385 bool has_upload() const;
387 // Set an extra request header by ID or name, or remove one by name. These
388 // methods may only be called before Start() is called, or before a new
389 // redirect in the request chain.
390 void SetExtraRequestHeaderById(int header_id, const std::string& value,
392 void SetExtraRequestHeaderByName(const std::string& name,
393 const std::string& value, bool overwrite);
394 void RemoveRequestHeaderByName(const std::string& name);
396 // Sets all extra request headers. Any extra request headers set by other
397 // methods are overwritten by this method. This method may only be called
398 // before Start() is called. It is an error to call it later.
399 void SetExtraRequestHeaders(const HttpRequestHeaders& headers);
401 const HttpRequestHeaders& extra_request_headers() const {
402 return extra_request_headers_;
405 // Gets the full request headers sent to the server.
407 // Return true and overwrites headers if it can get the request headers;
408 // otherwise, returns false and does not modify headers. (Always returns
409 // false for request types that don't have headers, like file requests.)
411 // This is guaranteed to succeed if:
413 // 1. A redirect or auth callback is currently running. Once it ends, the
414 // headers may become unavailable as a new request with the new address
415 // or credentials is made.
417 // 2. The OnResponseStarted callback is currently running or has run.
418 bool GetFullRequestHeaders(HttpRequestHeaders* headers) const;
420 // Gets the total amount of data received from network after SSL decoding and
422 int64 GetTotalReceivedBytes() const;
424 // Returns the current load state for the request. The returned value's
425 // |param| field is an optional parameter describing details related to the
426 // load state. Not all load states have a parameter.
427 LoadStateWithParam GetLoadState() const;
429 // Returns a partial representation of the request's state as a value, for
430 // debugging. Caller takes ownership of returned value.
431 base::Value* GetStateAsValue() const;
433 // Logs information about the what external object currently blocking the
434 // request. LogUnblocked must be called before resuming the request. This
435 // can be called multiple times in a row either with or without calling
436 // LogUnblocked between calls. |blocked_by| must not be NULL or have length
438 void LogBlockedBy(const char* blocked_by);
440 // Just like LogBlockedBy, but also makes GetLoadState return source as the
441 // |param| in the value returned by GetLoadState. Calling LogUnblocked or
442 // LogBlockedBy will clear the load param. |blocked_by| must not be NULL or
444 void LogAndReportBlockedBy(const char* blocked_by);
446 // Logs that the request is no longer blocked by the last caller to
450 // Returns the current upload progress in bytes. When the upload data is
451 // chunked, size is set to zero, but position will not be.
452 UploadProgress GetUploadProgress() const;
454 // Get response header(s) by ID or name. These methods may only be called
455 // once the delegate's OnResponseStarted method has been called. Headers
456 // that appear more than once in the response are coalesced, with values
457 // separated by commas (per RFC 2616). This will not work with cookies since
458 // comma can be used in cookie values.
459 // TODO(darin): add API to enumerate response headers.
460 void GetResponseHeaderById(int header_id, std::string* value);
461 void GetResponseHeaderByName(const std::string& name, std::string* value);
463 // Get all response headers, \n-delimited and \n\0-terminated. This includes
464 // the response status line. Restrictions on GetResponseHeaders apply.
465 void GetAllResponseHeaders(std::string* headers);
467 // The time when |this| was constructed.
468 base::TimeTicks creation_time() const { return creation_time_; }
470 // The time at which the returned response was requested. For cached
471 // responses, this is the last time the cache entry was validated.
472 const base::Time& request_time() const {
473 return response_info_.request_time;
476 // The time at which the returned response was generated. For cached
477 // responses, this is the last time the cache entry was validated.
478 const base::Time& response_time() const {
479 return response_info_.response_time;
482 // Indicate if this response was fetched from disk cache.
483 bool was_cached() const { return response_info_.was_cached; }
485 // Returns true if the URLRequest was delivered through a proxy.
486 bool was_fetched_via_proxy() const {
487 return response_info_.was_fetched_via_proxy;
490 // Returns true if the URLRequest was delivered over SPDY.
491 bool was_fetched_via_spdy() const {
492 return response_info_.was_fetched_via_spdy;
495 // Returns the host and port that the content was fetched from. See
496 // http_response_info.h for caveats relating to cached content.
497 HostPortPair GetSocketAddress() const;
499 // Get all response headers, as a HttpResponseHeaders object. See comments
500 // in HttpResponseHeaders class as to the format of the data.
501 HttpResponseHeaders* response_headers() const;
503 // Get the SSL connection info.
504 const SSLInfo& ssl_info() const {
505 return response_info_.ssl_info;
508 // Gets timing information related to the request. Events that have not yet
509 // occurred are left uninitialized. After a second request starts, due to
510 // a redirect or authentication, values will be reset.
512 // LoadTimingInfo only contains ConnectTiming information and socket IDs for
513 // non-cached HTTP responses.
514 void GetLoadTimingInfo(LoadTimingInfo* load_timing_info) const;
516 // Returns the cookie values included in the response, if the request is one
517 // that can have cookies. Returns true if the request is a cookie-bearing
518 // type, false otherwise. This method may only be called once the
519 // delegate's OnResponseStarted method has been called.
520 bool GetResponseCookies(ResponseCookies* cookies);
522 // Get the mime type. This method may only be called once the delegate's
523 // OnResponseStarted method has been called.
524 void GetMimeType(std::string* mime_type) const;
526 // Get the charset (character encoding). This method may only be called once
527 // the delegate's OnResponseStarted method has been called.
528 void GetCharset(std::string* charset) const;
530 // Returns the HTTP response code (e.g., 200, 404, and so on). This method
531 // may only be called once the delegate's OnResponseStarted method has been
532 // called. For non-HTTP requests, this method returns -1.
533 int GetResponseCode() const;
535 // Get the HTTP response info in its entirety.
536 const HttpResponseInfo& response_info() const { return response_info_; }
538 // Access the LOAD_* flags modifying this request (see load_flags.h).
539 int load_flags() const { return load_flags_; }
541 // The new flags may change the IGNORE_LIMITS flag only when called
542 // before Start() is called, it must only set the flag, and if set,
543 // the priority of this request must already be MAXIMUM_PRIORITY.
544 void SetLoadFlags(int flags);
546 // Returns true if the request is "pending" (i.e., if Start() has been called,
547 // and the response has not yet been called).
548 bool is_pending() const { return is_pending_; }
550 // Returns true if the request is in the process of redirecting to a new
551 // URL but has not yet initiated the new request.
552 bool is_redirecting() const { return is_redirecting_; }
554 // Returns the error status of the request.
555 const URLRequestStatus& status() const { return status_; }
557 // Returns a globally unique identifier for this request.
558 uint64 identifier() const { return identifier_; }
560 // This method is called to start the request. The delegate will receive
561 // a OnResponseStarted callback when the request is started.
564 // This method may be called at any time after Start() has been called to
565 // cancel the request. This method may be called many times, and it has
566 // no effect once the response has completed. It is guaranteed that no
567 // methods of the delegate will be called after the request has been
568 // cancelled, except that this may call the delegate's OnReadCompleted()
569 // during the call to Cancel itself.
572 // Cancels the request and sets the error to |error| (see net_error_list.h
574 void CancelWithError(int error);
576 // Cancels the request and sets the error to |error| (see net_error_list.h
577 // for values) and attaches |ssl_info| as the SSLInfo for that request. This
578 // is useful to attach a certificate and certificate error to a canceled
580 void CancelWithSSLError(int error, const SSLInfo& ssl_info);
582 // Read initiates an asynchronous read from the response, and must only
583 // be called after the OnResponseStarted callback is received with a
584 // successful status.
585 // If data is available, Read will return true, and the data and length will
586 // be returned immediately. If data is not available, Read returns false,
587 // and an asynchronous Read is initiated. The Read is finished when
588 // the caller receives the OnReadComplete callback. Unless the request was
589 // cancelled, OnReadComplete will always be called, even if the read failed.
591 // The buf parameter is a buffer to receive the data. If the operation
592 // completes asynchronously, the implementation will reference the buffer
593 // until OnReadComplete is called. The buffer must be at least max_bytes in
596 // The max_bytes parameter is the maximum number of bytes to read.
598 // The bytes_read parameter is an output parameter containing the
599 // the number of bytes read. A value of 0 indicates that there is no
600 // more data available to read from the stream.
602 // If a read error occurs, Read returns false and the request->status
603 // will be set to an error.
604 bool Read(IOBuffer* buf, int max_bytes, int* bytes_read);
606 // If this request is being cached by the HTTP cache, stop subsequent caching.
607 // Note that this method has no effect on other (simultaneous or not) requests
608 // for the same resource. The typical example is a request that results in
609 // the data being stored to disk (downloaded instead of rendered) so we don't
610 // want to store it twice.
613 // This method may be called to follow a redirect that was deferred in
614 // response to an OnReceivedRedirect call.
615 void FollowDeferredRedirect();
617 // This method must be called to resume network communications that were
618 // deferred in response to an OnBeforeNetworkStart call.
619 void ResumeNetworkStart();
621 // One of the following two methods should be called in response to an
622 // OnAuthRequired() callback (and only then).
623 // SetAuth will reissue the request with the given credentials.
624 // CancelAuth will give up and display the error page.
625 void SetAuth(const AuthCredentials& credentials);
628 // This method can be called after the user selects a client certificate to
629 // instruct this URLRequest to continue with the request with the
630 // certificate. Pass NULL if the user doesn't have a client certificate.
631 void ContinueWithCertificate(X509Certificate* client_cert);
633 // This method can be called after some error notifications to instruct this
634 // URLRequest to ignore the current error and continue with the request. To
635 // cancel the request instead, call Cancel().
636 void ContinueDespiteLastError();
638 // Used to specify the context (cookie store, cache) for this request.
639 const URLRequestContext* context() const;
641 const BoundNetLog& net_log() const { return net_log_; }
643 // Returns the expected content size if available
644 int64 GetExpectedContentSize() const;
646 // Returns the priority level for this request.
647 RequestPriority priority() const { return priority_; }
649 // Sets the priority level for this request and any related
650 // jobs. Must not change the priority to anything other than
651 // MAXIMUM_PRIORITY if the IGNORE_LIMITS load flag is set.
652 void SetPriority(RequestPriority priority);
654 // Returns true iff this request would be internally redirected to HTTPS
655 // due to HSTS. If so, |redirect_url| is rewritten to the new HTTPS URL.
656 bool GetHSTSRedirect(GURL* redirect_url) const;
658 // TODO(willchan): Undo this. Only temporarily public.
659 bool has_delegate() const { return delegate_ != NULL; }
661 // NOTE(willchan): This is just temporary for debugging
662 // http://crbug.com/90971.
663 // Allows to setting debug info into the URLRequest.
664 void set_stack_trace(const base::debug::StackTrace& stack_trace);
665 const base::debug::StackTrace* stack_trace() const;
667 void set_received_response_content_length(int64 received_content_length) {
668 received_response_content_length_ = received_content_length;
670 int64 received_response_content_length() const {
671 return received_response_content_length_;
674 // Available at NetworkDelegate::NotifyHeadersReceived() time, which is before
675 // the more general response_info() is available, even though it is a subset.
676 const HostPortPair& proxy_server() const {
677 return proxy_server_;
681 // Allow the URLRequestJob class to control the is_pending() flag.
682 void set_is_pending(bool value) { is_pending_ = value; }
684 // Allow the URLRequestJob class to set our status too
685 void set_status(const URLRequestStatus& value) { status_ = value; }
687 CookieStore* cookie_store() const { return cookie_store_.get(); }
689 // Allow the URLRequestJob to redirect this request. Returns OK if
690 // successful, otherwise an error code is returned.
691 int Redirect(const RedirectInfo& redirect_info);
693 // Called by URLRequestJob to allow interception when a redirect occurs.
694 void NotifyReceivedRedirect(const RedirectInfo& redirect_info,
695 bool* defer_redirect);
697 // Called by URLRequestHttpJob (note, only HTTP(S) jobs will call this) to
698 // allow deferral of network initialization.
699 void NotifyBeforeNetworkStart(bool* defer);
701 // Allow an interceptor's URLRequestJob to restart this request.
702 // Should only be called if the original job has not started a response.
706 friend class URLRequestJob;
707 friend class URLRequestContext;
709 // URLRequests are always created by calling URLRequestContext::CreateRequest.
711 // If no cookie store or network delegate are passed in, will use the ones
712 // from the URLRequestContext.
713 URLRequest(const GURL& url,
714 RequestPriority priority,
716 const URLRequestContext* context,
717 CookieStore* cookie_store,
718 NetworkDelegate* network_delegate);
720 // Registers or unregisters a network interception class.
721 static void RegisterRequestInterceptor(Interceptor* interceptor);
722 static void UnregisterRequestInterceptor(Interceptor* interceptor);
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
729 void BeforeRequestComplete(int error);
731 void StartJob(URLRequestJob* job);
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();
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
743 // Cancels the request and set the error and ssl info for this request to the
745 void DoCancel(int error, const SSLInfo& ssl_info);
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();
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();
756 // Called by URLRequestJob to allow interception when the final response
758 void NotifyResponseStarted();
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);
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;
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
781 void OnCallToDelegateComplete();
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_;
788 NetworkDelegate* network_delegate_;
790 // Tracks the time spent in various load states throughout this request.
791 BoundNetLog net_log_;
793 scoped_refptr<URLRequestJob> job_;
794 scoped_ptr<UploadDataStream> upload_data_stream_;
795 // TODO(mmenke): Make whether or not an upload is chunked transparent to the
797 ChunkedUploadDataStream* upload_chunked_data_stream_;
799 std::vector<GURL> url_chain_;
800 GURL first_party_for_cookies_;
801 GURL delegate_redirect_url_;
802 std::string method_; // "GET", "POST", etc. Should be all uppercase.
803 std::string referrer_;
804 ReferrerPolicy referrer_policy_;
805 FirstPartyURLPolicy first_party_url_policy_;
806 HttpRequestHeaders extra_request_headers_;
807 int load_flags_; // Flags indicating the request type for the load;
808 // expected values are LOAD_* enums above.
810 // Never access methods of the |delegate_| directly. Always use the
811 // Notify... methods for this.
814 // Current error status of the job. When no error has been encountered, this
815 // will be SUCCESS. If multiple errors have been encountered, this will be
816 // the first non-SUCCESS status seen.
817 URLRequestStatus status_;
819 // The HTTP response info, lazily initialized.
820 HttpResponseInfo response_info_;
822 // Tells us whether the job is outstanding. This is true from the time
823 // Start() is called to the time we dispatch RequestComplete and indicates
824 // whether the job is active.
827 // Indicates if the request is in the process of redirecting to a new
828 // location. It is true from the time the headers complete until a
829 // new request begins.
830 bool is_redirecting_;
832 // Number of times we're willing to redirect. Used to guard against
833 // infinite redirects.
836 // Cached value for use after we've orphaned the job handling the
837 // first transaction in a request involving redirects.
838 UploadProgress final_upload_progress_;
840 // The priority level for this request. Objects like
841 // ClientSocketPool use this to determine which URLRequest to
842 // allocate sockets to first.
843 RequestPriority priority_;
845 // TODO(battre): The only consumer of the identifier_ is currently the
846 // web request API. We need to match identifiers of requests between the
847 // web request API and the web navigation API. As the URLRequest does not
848 // exist when the web navigation API is triggered, the tracking probably
849 // needs to be done outside of the URLRequest anyway. Therefore, this
850 // identifier should be deleted here. http://crbug.com/89321
851 // A globally unique identifier for this request.
852 const uint64 identifier_;
854 // True if this request is currently calling a delegate, or is blocked waiting
855 // for the URL request or network delegate to resume it.
856 bool calling_delegate_;
858 // An optional parameter that provides additional information about what
859 // |this| is currently being blocked by.
860 std::string blocked_by_;
861 bool use_blocked_by_as_load_param_;
863 base::debug::LeakTracker<URLRequest> leak_tracker_;
865 // Callback passed to the network delegate to notify us when a blocked request
866 // is ready to be resumed or canceled.
867 CompletionCallback before_request_callback_;
869 // Safe-guard to ensure that we do not send multiple "I am completed"
870 // messages to network delegate.
871 // TODO(battre): Remove this. http://crbug.com/89049
872 bool has_notified_completion_;
874 // Authentication data used by the NetworkDelegate for this request,
875 // if one is present. |auth_credentials_| may be filled in when calling
876 // |NotifyAuthRequired| on the NetworkDelegate. |auth_info_| holds
877 // the authentication challenge being handled by |NotifyAuthRequired|.
878 AuthCredentials auth_credentials_;
879 scoped_refptr<AuthChallengeInfo> auth_info_;
881 int64 received_response_content_length_;
883 base::TimeTicks creation_time_;
885 // Timing information for the most recent request. Its start times are
886 // populated during Start(), and the rest are populated in OnResponseReceived.
887 LoadTimingInfo load_timing_info_;
889 scoped_ptr<const base::debug::StackTrace> stack_trace_;
891 // Keeps track of whether or not OnBeforeNetworkStart has been called yet.
892 bool notified_before_network_start_;
894 // The cookie store to be used for this request.
895 scoped_refptr<CookieStore> cookie_store_;
897 // The proxy server used for this request, if any.
898 HostPortPair proxy_server_;
900 DISALLOW_COPY_AND_ASSIGN(URLRequest);
905 #endif // NET_URL_REQUEST_URL_REQUEST_H_