Rename InputLatency::ScrollUpdate to Latency::ScrollUpdate
[chromium-blink-merge.git] / net / url_request / url_request.h
blobe623c202e71f1b0ed412e5998cd51f0015e3ab3b
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_
8 #include <string>
9 #include <vector>
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/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/log/net_log.h"
31 #include "net/url_request/url_request_status.h"
32 #include "url/gurl.h"
34 namespace base {
35 class Value;
37 namespace debug {
38 class StackTrace;
39 } // namespace debug
40 } // namespace base
42 namespace net {
44 class ChunkedUploadDataStream;
45 class CookieOptions;
46 class HostPortPair;
47 class IOBuffer;
48 struct LoadTimingInfo;
49 struct RedirectInfo;
50 class SSLCertRequestInfo;
51 class SSLInfo;
52 class UploadDataStream;
53 class URLRequestContext;
54 class URLRequestJob;
55 class X509Certificate;
57 // This stores the values of the Set-Cookie headers received during the request.
58 // Each item in the vector corresponds to a Set-Cookie: line received,
59 // excluding the "Set-Cookie:" part.
60 typedef std::vector<std::string> ResponseCookies;
62 //-----------------------------------------------------------------------------
63 // A class representing the asynchronous load of a data stream from an URL.
65 // The lifetime of an instance of this class is completely controlled by the
66 // consumer, and the instance is not required to live on the heap or be
67 // allocated in any special way. It is also valid to delete an URLRequest
68 // object during the handling of a callback to its delegate. Of course, once
69 // the URLRequest is deleted, no further callbacks to its delegate will occur.
71 // NOTE: All usage of all instances of this class should be on the same thread.
73 class NET_EXPORT URLRequest : NON_EXPORTED_BASE(public base::NonThreadSafe),
74 public base::SupportsUserData {
75 public:
76 // Callback function implemented by protocol handlers to create new jobs.
77 // The factory may return NULL to indicate an error, which will cause other
78 // factories to be queried. If no factory handles the request, then the
79 // default job will be used.
80 typedef URLRequestJob* (ProtocolFactory)(URLRequest* request,
81 NetworkDelegate* network_delegate,
82 const std::string& scheme);
84 // Referrer policies (see set_referrer_policy): During server redirects, the
85 // referrer header might be cleared, if the protocol changes from HTTPS to
86 // HTTP. This is the default behavior of URLRequest, corresponding to
87 // CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE. Alternatively, the
88 // referrer policy can be set to strip the referrer down to an origin upon
89 // cross-origin navigation (ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN), or
90 // never change the referrer header (NEVER_CLEAR_REFERRER). Embedders will
91 // want to use these options when implementing referrer policy support
92 // (https://w3c.github.io/webappsec/specs/referrer-policy/).
94 // REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN is a slight variant
95 // on CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE: If the request
96 // downgrades from HTTPS to HTTP, the referrer will be cleared. If the request
97 // transitions cross-origin (but does not downgrade), the referrer's
98 // granularity will be reduced (currently stripped down to an origin rather
99 // than a full URL). Same-origin requests will send the full referrer.
100 enum ReferrerPolicy {
101 CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
102 REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
103 ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
104 NEVER_CLEAR_REFERRER,
107 // First-party URL redirect policy: During server redirects, the first-party
108 // URL for cookies normally doesn't change. However, if the request is a
109 // top-level first-party request, the first-party URL should be updated to the
110 // URL on every redirect.
111 enum FirstPartyURLPolicy {
112 NEVER_CHANGE_FIRST_PARTY_URL,
113 UPDATE_FIRST_PARTY_URL_ON_REDIRECT,
116 // The delegate's methods are called from the message loop of the thread
117 // on which the request's Start() method is called. See above for the
118 // ordering of callbacks.
120 // The callbacks will be called in the following order:
121 // Start()
122 // - OnCertificateRequested* (zero or more calls, if the SSL server and/or
123 // SSL proxy requests a client certificate for authentication)
124 // - OnSSLCertificateError* (zero or one call, if the SSL server's
125 // certificate has an error)
126 // - OnReceivedRedirect* (zero or more calls, for the number of redirects)
127 // - OnAuthRequired* (zero or more calls, for the number of
128 // authentication failures)
129 // - OnResponseStarted
130 // Read() initiated by delegate
131 // - OnReadCompleted* (zero or more calls until all data is read)
133 // Read() must be called at least once. Read() returns true when it completed
134 // immediately, and false if an IO is pending or if there is an error. When
135 // Read() returns false, the caller can check the Request's status() to see
136 // if an error occurred, or if the IO is just pending. When Read() returns
137 // true with zero bytes read, it indicates the end of the response.
139 class NET_EXPORT Delegate {
140 public:
141 // Called upon receiving a redirect. The delegate may call the request's
142 // Cancel method to prevent the redirect from being followed. Since there
143 // may be multiple chained redirects, there may also be more than one
144 // redirect call.
146 // When this function is called, the request will still contain the
147 // original URL, the destination of the redirect is provided in 'new_url'.
148 // If the delegate does not cancel the request and |*defer_redirect| is
149 // false, then the redirect will be followed, and the request's URL will be
150 // changed to the new URL. Otherwise if the delegate does not cancel the
151 // request and |*defer_redirect| is true, then the redirect will be
152 // followed once FollowDeferredRedirect is called on the URLRequest.
154 // The caller must set |*defer_redirect| to false, so that delegates do not
155 // need to set it if they are happy with the default behavior of not
156 // deferring redirect.
157 virtual void OnReceivedRedirect(URLRequest* request,
158 const RedirectInfo& redirect_info,
159 bool* defer_redirect);
161 // Called when we receive an authentication failure. The delegate should
162 // call request->SetAuth() with the user's credentials once it obtains them,
163 // or request->CancelAuth() to cancel the login and display the error page.
164 // When it does so, the request will be reissued, restarting the sequence
165 // of On* callbacks.
166 virtual void OnAuthRequired(URLRequest* request,
167 AuthChallengeInfo* auth_info);
169 // Called when we receive an SSL CertificateRequest message for client
170 // authentication. The delegate should call
171 // request->ContinueWithCertificate() with the client certificate the user
172 // selected, or request->ContinueWithCertificate(NULL) to continue the SSL
173 // handshake without a client certificate.
174 virtual void OnCertificateRequested(
175 URLRequest* request,
176 SSLCertRequestInfo* cert_request_info);
178 // Called when using SSL and the server responds with a certificate with
179 // an error, for example, whose common name does not match the common name
180 // we were expecting for that host. The delegate should either do the
181 // safe thing and Cancel() the request or decide to proceed by calling
182 // ContinueDespiteLastError(). cert_error is a ERR_* error code
183 // indicating what's wrong with the certificate.
184 // If |fatal| is true then the host in question demands a higher level
185 // of security (due e.g. to HTTP Strict Transport Security, user
186 // preference, or built-in policy). In this case, errors must not be
187 // bypassable by the user.
188 virtual void OnSSLCertificateError(URLRequest* request,
189 const SSLInfo& ssl_info,
190 bool fatal);
192 // Called to notify that the request must use the network to complete the
193 // request and is about to do so. This is called at most once per
194 // URLRequest, and by default does not defer. If deferred, call
195 // ResumeNetworkStart() to continue or Cancel() to cancel.
196 virtual void OnBeforeNetworkStart(URLRequest* request, bool* defer);
198 // After calling Start(), the delegate will receive an OnResponseStarted
199 // callback when the request has completed. If an error occurred, the
200 // request->status() will be set. On success, all redirects have been
201 // followed and the final response is beginning to arrive. At this point,
202 // meta data about the response is available, including for example HTTP
203 // response headers if this is a request for a HTTP resource.
204 virtual void OnResponseStarted(URLRequest* request) = 0;
206 // Called when the a Read of the response body is completed after an
207 // IO_PENDING status from a Read() call.
208 // The data read is filled into the buffer which the caller passed
209 // to Read() previously.
211 // If an error occurred, request->status() will contain the error,
212 // and bytes read will be -1.
213 virtual void OnReadCompleted(URLRequest* request, int bytes_read) = 0;
215 protected:
216 virtual ~Delegate() {}
219 // If destroyed after Start() has been called but while IO is pending,
220 // then the request will be effectively canceled and the delegate
221 // will not have any more of its methods called.
222 ~URLRequest() override;
224 // Changes the default cookie policy from allowing all cookies to blocking all
225 // cookies. Embedders that want to implement a more flexible policy should
226 // change the default to blocking all cookies, and provide a NetworkDelegate
227 // with the URLRequestContext that maintains the CookieStore.
228 // The cookie policy default has to be set before the first URLRequest is
229 // started. Once it was set to block all cookies, it cannot be changed back.
230 static void SetDefaultCookiePolicyToBlock();
232 // Returns true if the scheme can be handled by URLRequest. False otherwise.
233 static bool IsHandledProtocol(const std::string& scheme);
235 // Returns true if the url can be handled by URLRequest. False otherwise.
236 // The function returns true for invalid urls because URLRequest knows how
237 // to handle those.
238 // NOTE: This will also return true for URLs that are handled by
239 // ProtocolFactories that only work for requests that are scoped to a
240 // Profile.
241 static bool IsHandledURL(const GURL& url);
243 // The original url is the url used to initialize the request, and it may
244 // differ from the url if the request was redirected.
245 const GURL& original_url() const { return url_chain_.front(); }
246 // The chain of urls traversed by this request. If the request had no
247 // redirects, this vector will contain one element.
248 const std::vector<GURL>& url_chain() const { return url_chain_; }
249 const GURL& url() const { return url_chain_.back(); }
251 // The URL that should be consulted for the third-party cookie blocking
252 // policy.
254 // WARNING: This URL must only be used for the third-party cookie blocking
255 // policy. It MUST NEVER be used for any kind of SECURITY check.
257 // For example, if a top-level navigation is redirected, the
258 // first-party for cookies will be the URL of the first URL in the
259 // redirect chain throughout the whole redirect. If it was used for
260 // a security check, an attacker might try to get around this check
261 // by starting from some page that redirects to the
262 // host-to-be-attacked.
263 const GURL& first_party_for_cookies() const {
264 return first_party_for_cookies_;
266 // This method may only be called before Start().
267 void set_first_party_for_cookies(const GURL& first_party_for_cookies);
269 // The first-party URL policy to apply when updating the first party URL
270 // during redirects. The first-party URL policy may only be changed before
271 // Start() is called.
272 FirstPartyURLPolicy first_party_url_policy() const {
273 return first_party_url_policy_;
275 void set_first_party_url_policy(FirstPartyURLPolicy first_party_url_policy);
277 // The request method, as an uppercase string. "GET" is the default value.
278 // The request method may only be changed before Start() is called and
279 // should only be assigned an uppercase value.
280 const std::string& method() const { return method_; }
281 void set_method(const std::string& method);
283 // The referrer URL for the request. This header may actually be suppressed
284 // from the underlying network request for security reasons (e.g., a HTTPS
285 // URL will not be sent as the referrer for a HTTP request). The referrer
286 // may only be changed before Start() is called.
287 const std::string& referrer() const { return referrer_; }
288 // Referrer is sanitized to remove URL fragment, user name and password.
289 void SetReferrer(const std::string& referrer);
291 // The referrer policy to apply when updating the referrer during redirects.
292 // The referrer policy may only be changed before Start() is called.
293 ReferrerPolicy referrer_policy() const { return referrer_policy_; }
294 void set_referrer_policy(ReferrerPolicy referrer_policy);
296 // Sets the delegate of the request. This value may be changed at any time,
297 // and it is permissible for it to be null.
298 void set_delegate(Delegate* delegate);
300 // Indicates that the request body should be sent using chunked transfer
301 // encoding. This method may only be called before Start() is called.
302 void EnableChunkedUpload();
304 // Appends the given bytes to the request's upload data to be sent
305 // immediately via chunked transfer encoding. When all data has been added,
306 // set |is_last_chunk| to true to indicate the end of upload data. All chunks
307 // but the last must have |bytes_len| > 0.
309 // This method may be called only after calling EnableChunkedUpload().
311 // Despite the name of this method, over-the-wire chunk boundaries will most
312 // likely not match the "chunks" appended with this function.
313 void AppendChunkToUpload(const char* bytes,
314 int bytes_len,
315 bool is_last_chunk);
317 // Sets the upload data.
318 void set_upload(scoped_ptr<UploadDataStream> upload);
320 // Gets the upload data.
321 const UploadDataStream* get_upload() const;
323 // Returns true if the request has a non-empty message body to upload.
324 bool has_upload() const;
326 // Set or remove a extra request header. These methods may only be called
327 // before Start() is called, or between receiving a redirect and trying to
328 // follow it.
329 void SetExtraRequestHeaderByName(const std::string& name,
330 const std::string& value, bool overwrite);
331 void RemoveRequestHeaderByName(const std::string& name);
333 // Sets all extra request headers. Any extra request headers set by other
334 // methods are overwritten by this method. This method may only be called
335 // before Start() is called. It is an error to call it later.
336 void SetExtraRequestHeaders(const HttpRequestHeaders& headers);
338 const HttpRequestHeaders& extra_request_headers() const {
339 return extra_request_headers_;
342 // Gets the full request headers sent to the server.
344 // Return true and overwrites headers if it can get the request headers;
345 // otherwise, returns false and does not modify headers. (Always returns
346 // false for request types that don't have headers, like file requests.)
348 // This is guaranteed to succeed if:
350 // 1. A redirect or auth callback is currently running. Once it ends, the
351 // headers may become unavailable as a new request with the new address
352 // or credentials is made.
354 // 2. The OnResponseStarted callback is currently running or has run.
355 bool GetFullRequestHeaders(HttpRequestHeaders* headers) const;
357 // Gets the total amount of data received from network after SSL decoding and
358 // proxy handling.
359 int64 GetTotalReceivedBytes() const;
361 // Returns the current load state for the request. The returned value's
362 // |param| field is an optional parameter describing details related to the
363 // load state. Not all load states have a parameter.
364 LoadStateWithParam GetLoadState() const;
366 // Returns a partial representation of the request's state as a value, for
367 // debugging. Caller takes ownership of returned value.
368 base::Value* GetStateAsValue() const;
370 // Logs information about the what external object currently blocking the
371 // request. LogUnblocked must be called before resuming the request. This
372 // can be called multiple times in a row either with or without calling
373 // LogUnblocked between calls. |blocked_by| must not be NULL or have length
374 // 0.
375 void LogBlockedBy(const char* blocked_by);
377 // Just like LogBlockedBy, but also makes GetLoadState return source as the
378 // |param| in the value returned by GetLoadState. Calling LogUnblocked or
379 // LogBlockedBy will clear the load param. |blocked_by| must not be NULL or
380 // have length 0.
381 void LogAndReportBlockedBy(const char* blocked_by);
383 // Logs that the request is no longer blocked by the last caller to
384 // LogBlockedBy.
385 void LogUnblocked();
387 // Returns the current upload progress in bytes. When the upload data is
388 // chunked, size is set to zero, but position will not be.
389 UploadProgress GetUploadProgress() const;
391 // Get response header(s) by name. This method may only be called
392 // once the delegate's OnResponseStarted method has been called. Headers
393 // that appear more than once in the response are coalesced, with values
394 // separated by commas (per RFC 2616). This will not work with cookies since
395 // comma can be used in cookie values.
396 void GetResponseHeaderByName(const std::string& name, std::string* value);
398 // The time when |this| was constructed.
399 base::TimeTicks creation_time() const { return creation_time_; }
401 // The time at which the returned response was requested. For cached
402 // responses, this is the last time the cache entry was validated.
403 const base::Time& request_time() const {
404 return response_info_.request_time;
407 // The time at which the returned response was generated. For cached
408 // responses, this is the last time the cache entry was validated.
409 const base::Time& response_time() const {
410 return response_info_.response_time;
413 // Indicate if this response was fetched from disk cache.
414 bool was_cached() const { return response_info_.was_cached; }
416 // Returns true if the URLRequest was delivered through a proxy.
417 bool was_fetched_via_proxy() const {
418 return response_info_.was_fetched_via_proxy;
421 // Returns true if the URLRequest was delivered over SPDY.
422 bool was_fetched_via_spdy() const {
423 return response_info_.was_fetched_via_spdy;
426 // Returns the host and port that the content was fetched from. See
427 // http_response_info.h for caveats relating to cached content.
428 HostPortPair GetSocketAddress() const;
430 // Get all response headers, as a HttpResponseHeaders object. See comments
431 // in HttpResponseHeaders class as to the format of the data.
432 HttpResponseHeaders* response_headers() const;
434 // Get the SSL connection info.
435 const SSLInfo& ssl_info() const {
436 return response_info_.ssl_info;
439 // Gets timing information related to the request. Events that have not yet
440 // occurred are left uninitialized. After a second request starts, due to
441 // a redirect or authentication, values will be reset.
443 // LoadTimingInfo only contains ConnectTiming information and socket IDs for
444 // non-cached HTTP responses.
445 void GetLoadTimingInfo(LoadTimingInfo* load_timing_info) const;
447 // Returns the cookie values included in the response, if the request is one
448 // that can have cookies. Returns true if the request is a cookie-bearing
449 // type, false otherwise. This method may only be called once the
450 // delegate's OnResponseStarted method has been called.
451 bool GetResponseCookies(ResponseCookies* cookies);
453 // Get the mime type. This method may only be called once the delegate's
454 // OnResponseStarted method has been called.
455 void GetMimeType(std::string* mime_type) const;
457 // Get the charset (character encoding). This method may only be called once
458 // the delegate's OnResponseStarted method has been called.
459 void GetCharset(std::string* charset) const;
461 // Returns the HTTP response code (e.g., 200, 404, and so on). This method
462 // may only be called once the delegate's OnResponseStarted method has been
463 // called. For non-HTTP requests, this method returns -1.
464 int GetResponseCode() const;
466 // Get the HTTP response info in its entirety.
467 const HttpResponseInfo& response_info() const { return response_info_; }
469 // Access the LOAD_* flags modifying this request (see load_flags.h).
470 int load_flags() const { return load_flags_; }
472 // The new flags may change the IGNORE_LIMITS flag only when called
473 // before Start() is called, it must only set the flag, and if set,
474 // the priority of this request must already be MAXIMUM_PRIORITY.
475 void SetLoadFlags(int flags);
477 // Returns true if the request is "pending" (i.e., if Start() has been called,
478 // and the response has not yet been called).
479 bool is_pending() const { return is_pending_; }
481 // Returns true if the request is in the process of redirecting to a new
482 // URL but has not yet initiated the new request.
483 bool is_redirecting() const { return is_redirecting_; }
485 // Returns the error status of the request.
486 const URLRequestStatus& status() const { return status_; }
488 // Returns a globally unique identifier for this request.
489 uint64 identifier() const { return identifier_; }
491 // This method is called to start the request. The delegate will receive
492 // a OnResponseStarted callback when the request is started.
493 void Start();
495 // This method may be called at any time after Start() has been called to
496 // cancel the request. This method may be called many times, and it has
497 // no effect once the response has completed. It is guaranteed that no
498 // methods of the delegate will be called after the request has been
499 // cancelled, except that this may call the delegate's OnReadCompleted()
500 // during the call to Cancel itself.
501 void Cancel();
503 // Cancels the request and sets the error to |error| (see net_error_list.h
504 // for values).
505 void CancelWithError(int error);
507 // Cancels the request and sets the error to |error| (see net_error_list.h
508 // for values) and attaches |ssl_info| as the SSLInfo for that request. This
509 // is useful to attach a certificate and certificate error to a canceled
510 // request.
511 void CancelWithSSLError(int error, const SSLInfo& ssl_info);
513 // Read initiates an asynchronous read from the response, and must only
514 // be called after the OnResponseStarted callback is received with a
515 // successful status.
516 // If data is available, Read will return true, and the data and length will
517 // be returned immediately. If data is not available, Read returns false,
518 // and an asynchronous Read is initiated. The Read is finished when
519 // the caller receives the OnReadComplete callback. Unless the request was
520 // cancelled, OnReadComplete will always be called, even if the read failed.
522 // The buf parameter is a buffer to receive the data. If the operation
523 // completes asynchronously, the implementation will reference the buffer
524 // until OnReadComplete is called. The buffer must be at least max_bytes in
525 // length.
527 // The max_bytes parameter is the maximum number of bytes to read.
529 // The bytes_read parameter is an output parameter containing the
530 // the number of bytes read. A value of 0 indicates that there is no
531 // more data available to read from the stream.
533 // If a read error occurs, Read returns false and the request->status
534 // will be set to an error.
535 bool Read(IOBuffer* buf, int max_bytes, int* bytes_read);
537 // If this request is being cached by the HTTP cache, stop subsequent caching.
538 // Note that this method has no effect on other (simultaneous or not) requests
539 // for the same resource. The typical example is a request that results in
540 // the data being stored to disk (downloaded instead of rendered) so we don't
541 // want to store it twice.
542 void StopCaching();
544 // This method may be called to follow a redirect that was deferred in
545 // response to an OnReceivedRedirect call.
546 void FollowDeferredRedirect();
548 // This method must be called to resume network communications that were
549 // deferred in response to an OnBeforeNetworkStart call.
550 void ResumeNetworkStart();
552 // One of the following two methods should be called in response to an
553 // OnAuthRequired() callback (and only then).
554 // SetAuth will reissue the request with the given credentials.
555 // CancelAuth will give up and display the error page.
556 void SetAuth(const AuthCredentials& credentials);
557 void CancelAuth();
559 // This method can be called after the user selects a client certificate to
560 // instruct this URLRequest to continue with the request with the
561 // certificate. Pass NULL if the user doesn't have a client certificate.
562 void ContinueWithCertificate(X509Certificate* client_cert);
564 // This method can be called after some error notifications to instruct this
565 // URLRequest to ignore the current error and continue with the request. To
566 // cancel the request instead, call Cancel().
567 void ContinueDespiteLastError();
569 // Used to specify the context (cookie store, cache) for this request.
570 const URLRequestContext* context() const;
572 const BoundNetLog& net_log() const { return net_log_; }
574 // Returns the expected content size if available
575 int64 GetExpectedContentSize() const;
577 // Returns the priority level for this request.
578 RequestPriority priority() const { return priority_; }
580 // Sets the priority level for this request and any related
581 // jobs. Must not change the priority to anything other than
582 // MAXIMUM_PRIORITY if the IGNORE_LIMITS load flag is set.
583 void SetPriority(RequestPriority priority);
585 // Returns true iff this request would be internally redirected to HTTPS
586 // due to HSTS. If so, |redirect_url| is rewritten to the new HTTPS URL.
587 bool GetHSTSRedirect(GURL* redirect_url) const;
589 // TODO(willchan): Undo this. Only temporarily public.
590 bool has_delegate() const { return delegate_ != NULL; }
592 // NOTE(willchan): This is just temporary for debugging
593 // http://crbug.com/90971.
594 // Allows to setting debug info into the URLRequest.
595 void set_stack_trace(const base::debug::StackTrace& stack_trace);
596 const base::debug::StackTrace* stack_trace() const;
598 void set_received_response_content_length(int64 received_content_length) {
599 received_response_content_length_ = received_content_length;
601 int64 received_response_content_length() const {
602 return received_response_content_length_;
605 // Available at NetworkDelegate::NotifyHeadersReceived() time, which is before
606 // the more general response_info() is available, even though it is a subset.
607 const HostPortPair& proxy_server() const {
608 return proxy_server_;
611 protected:
612 // Allow the URLRequestJob class to control the is_pending() flag.
613 void set_is_pending(bool value) { is_pending_ = value; }
615 // Allow the URLRequestJob class to set our status too
616 void set_status(const URLRequestStatus& value) { status_ = value; }
618 // Allow the URLRequestJob to redirect this request. Returns OK if
619 // successful, otherwise an error code is returned.
620 int Redirect(const RedirectInfo& redirect_info);
622 // Called by URLRequestJob to allow interception when a redirect occurs.
623 void NotifyReceivedRedirect(const RedirectInfo& redirect_info,
624 bool* defer_redirect);
626 // Called by URLRequestHttpJob (note, only HTTP(S) jobs will call this) to
627 // allow deferral of network initialization.
628 void NotifyBeforeNetworkStart(bool* defer);
630 // Allow an interceptor's URLRequestJob to restart this request.
631 // Should only be called if the original job has not started a response.
632 void Restart();
634 private:
635 friend class URLRequestJob;
636 friend class URLRequestContext;
638 // URLRequests are always created by calling URLRequestContext::CreateRequest.
640 // If no network delegate is passed in, will use the ones from the
641 // URLRequestContext.
642 URLRequest(const GURL& url,
643 RequestPriority priority,
644 Delegate* delegate,
645 const URLRequestContext* context,
646 NetworkDelegate* network_delegate);
648 // Resumes or blocks a request paused by the NetworkDelegate::OnBeforeRequest
649 // handler. If |blocked| is true, the request is blocked and an error page is
650 // returned indicating so. This should only be called after Start is called
651 // and OnBeforeRequest returns true (signalling that the request should be
652 // paused).
653 void BeforeRequestComplete(int error);
655 void StartJob(URLRequestJob* job);
657 // Restarting involves replacing the current job with a new one such as what
658 // happens when following a HTTP redirect.
659 void RestartWithJob(URLRequestJob* job);
660 void PrepareToRestart();
662 // Detaches the job from this request in preparation for this object going
663 // away or the job being replaced. The job will not call us back when it has
664 // been orphaned.
665 void OrphanJob();
667 // Cancels the request and set the error and ssl info for this request to the
668 // passed values.
669 void DoCancel(int error, const SSLInfo& ssl_info);
671 // Called by the URLRequestJob when the headers are received, before any other
672 // method, to allow caching of load timing information.
673 void OnHeadersComplete();
675 // Notifies the network delegate that the request has been completed.
676 // This does not imply a successful completion. Also a canceled request is
677 // considered completed.
678 void NotifyRequestCompleted();
680 // Called by URLRequestJob to allow interception when the final response
681 // occurs.
682 void NotifyResponseStarted();
684 // These functions delegate to |delegate_| and may only be used if
685 // |delegate_| is not NULL. See URLRequest::Delegate for the meaning
686 // of these functions.
687 void NotifyAuthRequired(AuthChallengeInfo* auth_info);
688 void NotifyAuthRequiredComplete(NetworkDelegate::AuthRequiredResponse result);
689 void NotifyCertificateRequested(SSLCertRequestInfo* cert_request_info);
690 void NotifySSLCertificateError(const SSLInfo& ssl_info, bool fatal);
691 void NotifyReadCompleted(int bytes_read);
693 // These functions delegate to |network_delegate_| if it is not NULL.
694 // If |network_delegate_| is NULL, cookies can be used unless
695 // SetDefaultCookiePolicyToBlock() has been called.
696 bool CanGetCookies(const CookieList& cookie_list) const;
697 bool CanSetCookie(const std::string& cookie_line,
698 CookieOptions* options) const;
699 bool CanEnablePrivacyMode() const;
701 // Called just before calling a delegate that may block a request.
702 void OnCallToDelegate();
703 // Called when the delegate lets a request continue. Also called on
704 // cancellation.
705 void OnCallToDelegateComplete();
707 // Contextual information used for this request. Cannot be NULL. This contains
708 // most of the dependencies which are shared between requests (disk cache,
709 // cookie store, socket pool, etc.)
710 const URLRequestContext* context_;
712 NetworkDelegate* network_delegate_;
714 // Tracks the time spent in various load states throughout this request.
715 BoundNetLog net_log_;
717 scoped_refptr<URLRequestJob> job_;
718 scoped_ptr<UploadDataStream> upload_data_stream_;
719 // TODO(mmenke): Make whether or not an upload is chunked transparent to the
720 // URLRequest.
721 ChunkedUploadDataStream* upload_chunked_data_stream_;
723 std::vector<GURL> url_chain_;
724 GURL first_party_for_cookies_;
725 GURL delegate_redirect_url_;
726 std::string method_; // "GET", "POST", etc. Should be all uppercase.
727 std::string referrer_;
728 ReferrerPolicy referrer_policy_;
729 FirstPartyURLPolicy first_party_url_policy_;
730 HttpRequestHeaders extra_request_headers_;
731 int load_flags_; // Flags indicating the request type for the load;
732 // expected values are LOAD_* enums above.
734 // Never access methods of the |delegate_| directly. Always use the
735 // Notify... methods for this.
736 Delegate* delegate_;
738 // Current error status of the job. When no error has been encountered, this
739 // will be SUCCESS. If multiple errors have been encountered, this will be
740 // the first non-SUCCESS status seen.
741 URLRequestStatus status_;
743 // The HTTP response info, lazily initialized.
744 HttpResponseInfo response_info_;
746 // Tells us whether the job is outstanding. This is true from the time
747 // Start() is called to the time we dispatch RequestComplete and indicates
748 // whether the job is active.
749 bool is_pending_;
751 // Indicates if the request is in the process of redirecting to a new
752 // location. It is true from the time the headers complete until a
753 // new request begins.
754 bool is_redirecting_;
756 // Number of times we're willing to redirect. Used to guard against
757 // infinite redirects.
758 int redirect_limit_;
760 // Cached value for use after we've orphaned the job handling the
761 // first transaction in a request involving redirects.
762 UploadProgress final_upload_progress_;
764 // The priority level for this request. Objects like
765 // ClientSocketPool use this to determine which URLRequest to
766 // allocate sockets to first.
767 RequestPriority priority_;
769 // TODO(battre): The only consumer of the identifier_ is currently the
770 // web request API. We need to match identifiers of requests between the
771 // web request API and the web navigation API. As the URLRequest does not
772 // exist when the web navigation API is triggered, the tracking probably
773 // needs to be done outside of the URLRequest anyway. Therefore, this
774 // identifier should be deleted here. http://crbug.com/89321
775 // A globally unique identifier for this request.
776 const uint64 identifier_;
778 // True if this request is currently calling a delegate, or is blocked waiting
779 // for the URL request or network delegate to resume it.
780 bool calling_delegate_;
782 // An optional parameter that provides additional information about what
783 // |this| is currently being blocked by.
784 std::string blocked_by_;
785 bool use_blocked_by_as_load_param_;
787 base::debug::LeakTracker<URLRequest> leak_tracker_;
789 // Callback passed to the network delegate to notify us when a blocked request
790 // is ready to be resumed or canceled.
791 CompletionCallback before_request_callback_;
793 // Safe-guard to ensure that we do not send multiple "I am completed"
794 // messages to network delegate.
795 // TODO(battre): Remove this. http://crbug.com/89049
796 bool has_notified_completion_;
798 // Authentication data used by the NetworkDelegate for this request,
799 // if one is present. |auth_credentials_| may be filled in when calling
800 // |NotifyAuthRequired| on the NetworkDelegate. |auth_info_| holds
801 // the authentication challenge being handled by |NotifyAuthRequired|.
802 AuthCredentials auth_credentials_;
803 scoped_refptr<AuthChallengeInfo> auth_info_;
805 int64 received_response_content_length_;
807 base::TimeTicks creation_time_;
809 // Timing information for the most recent request. Its start times are
810 // populated during Start(), and the rest are populated in OnResponseReceived.
811 LoadTimingInfo load_timing_info_;
813 scoped_ptr<const base::debug::StackTrace> stack_trace_;
815 // Keeps track of whether or not OnBeforeNetworkStart has been called yet.
816 bool notified_before_network_start_;
818 // The proxy server used for this request, if any.
819 HostPortPair proxy_server_;
821 DISALLOW_COPY_AND_ASSIGN(URLRequest);
824 } // namespace net
826 #endif // NET_URL_REQUEST_URL_REQUEST_H_