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