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