Blink roll 25b6bd3a7a131ffe68d809546ad1a20707915cdc:3a503f41ae42e5b79cfcd2ff10e65afde...
[chromium-blink-merge.git] / net / url_request / url_request.h
blobaf972bd2df7c15500b429c99b22e16b28bd55f9e
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/net_log.h"
25 #include "net/base/network_delegate.h"
26 #include "net/base/request_priority.h"
27 #include "net/base/upload_progress.h"
28 #include "net/cookies/canonical_cookie.h"
29 #include "net/cookies/cookie_store.h"
30 #include "net/http/http_request_headers.h"
31 #include "net/http/http_response_info.h"
32 #include "net/url_request/url_request_status.h"
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 // HTTP request/response header IDs (via some preprocessor fun) for use with
86 // SetRequestHeaderById and GetResponseHeaderById.
87 enum {
88 #define HTTP_ATOM(x) HTTP_ ## x,
89 #include "net/http/http_atom_list.h"
90 #undef HTTP_ATOM
93 // Referrer policies (see set_referrer_policy): During server redirects, the
94 // referrer header might be cleared, if the protocol changes from HTTPS to
95 // HTTP. This is the default behavior of URLRequest, corresponding to
96 // CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE. Alternatively, the
97 // referrer policy can be set to strip the referrer down to an origin upon
98 // cross-origin navigation (ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN), or
99 // never change the referrer header (NEVER_CLEAR_REFERRER). Embedders will
100 // want to use these options when implementing referrer policy support
101 // (https://w3c.github.io/webappsec/specs/referrer-policy/).
103 // REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN is a slight variant
104 // on CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE: If the request
105 // downgrades from HTTPS to HTTP, the referrer will be cleared. If the request
106 // transitions cross-origin (but does not downgrade), the referrer's
107 // granularity will be reduced (currently stripped down to an origin rather
108 // than a full URL). Same-origin requests will send the full referrer.
109 enum ReferrerPolicy {
110 CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
111 REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
112 ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
113 NEVER_CLEAR_REFERRER,
116 // First-party URL redirect policy: During server redirects, the first-party
117 // URL for cookies normally doesn't change. However, if the request is a
118 // top-level first-party request, the first-party URL should be updated to the
119 // URL on every redirect.
120 enum FirstPartyURLPolicy {
121 NEVER_CHANGE_FIRST_PARTY_URL,
122 UPDATE_FIRST_PARTY_URL_ON_REDIRECT,
125 // The delegate's methods are called from the message loop of the thread
126 // on which the request's Start() method is called. See above for the
127 // ordering of callbacks.
129 // The callbacks will be called in the following order:
130 // Start()
131 // - OnCertificateRequested* (zero or more calls, if the SSL server and/or
132 // SSL proxy requests a client certificate for authentication)
133 // - OnSSLCertificateError* (zero or one call, if the SSL server's
134 // certificate has an error)
135 // - OnReceivedRedirect* (zero or more calls, for the number of redirects)
136 // - OnAuthRequired* (zero or more calls, for the number of
137 // authentication failures)
138 // - OnResponseStarted
139 // Read() initiated by delegate
140 // - OnReadCompleted* (zero or more calls until all data is read)
142 // Read() must be called at least once. Read() returns true when it completed
143 // immediately, and false if an IO is pending or if there is an error. When
144 // Read() returns false, the caller can check the Request's status() to see
145 // if an error occurred, or if the IO is just pending. When Read() returns
146 // true with zero bytes read, it indicates the end of the response.
148 class NET_EXPORT Delegate {
149 public:
150 // Called upon receiving a redirect. The delegate may call the request's
151 // Cancel method to prevent the redirect from being followed. Since there
152 // may be multiple chained redirects, there may also be more than one
153 // redirect call.
155 // When this function is called, the request will still contain the
156 // original URL, the destination of the redirect is provided in 'new_url'.
157 // If the delegate does not cancel the request and |*defer_redirect| is
158 // false, then the redirect will be followed, and the request's URL will be
159 // changed to the new URL. Otherwise if the delegate does not cancel the
160 // request and |*defer_redirect| is true, then the redirect will be
161 // followed once FollowDeferredRedirect is called on the URLRequest.
163 // The caller must set |*defer_redirect| to false, so that delegates do not
164 // need to set it if they are happy with the default behavior of not
165 // deferring redirect.
166 virtual void OnReceivedRedirect(URLRequest* request,
167 const RedirectInfo& redirect_info,
168 bool* defer_redirect);
170 // Called when we receive an authentication failure. The delegate should
171 // call request->SetAuth() with the user's credentials once it obtains them,
172 // or request->CancelAuth() to cancel the login and display the error page.
173 // When it does so, the request will be reissued, restarting the sequence
174 // of On* callbacks.
175 virtual void OnAuthRequired(URLRequest* request,
176 AuthChallengeInfo* auth_info);
178 // Called when we receive an SSL CertificateRequest message for client
179 // authentication. The delegate should call
180 // request->ContinueWithCertificate() with the client certificate the user
181 // selected, or request->ContinueWithCertificate(NULL) to continue the SSL
182 // handshake without a client certificate.
183 virtual void OnCertificateRequested(
184 URLRequest* request,
185 SSLCertRequestInfo* cert_request_info);
187 // Called when using SSL and the server responds with a certificate with
188 // an error, for example, whose common name does not match the common name
189 // we were expecting for that host. The delegate should either do the
190 // safe thing and Cancel() the request or decide to proceed by calling
191 // ContinueDespiteLastError(). cert_error is a ERR_* error code
192 // indicating what's wrong with the certificate.
193 // If |fatal| is true then the host in question demands a higher level
194 // of security (due e.g. to HTTP Strict Transport Security, user
195 // preference, or built-in policy). In this case, errors must not be
196 // bypassable by the user.
197 virtual void OnSSLCertificateError(URLRequest* request,
198 const SSLInfo& ssl_info,
199 bool fatal);
201 // Called to notify that the request must use the network to complete the
202 // request and is about to do so. This is called at most once per
203 // URLRequest, and by default does not defer. If deferred, call
204 // ResumeNetworkStart() to continue or Cancel() to cancel.
205 virtual void OnBeforeNetworkStart(URLRequest* request, bool* defer);
207 // After calling Start(), the delegate will receive an OnResponseStarted
208 // callback when the request has completed. If an error occurred, the
209 // request->status() will be set. On success, all redirects have been
210 // followed and the final response is beginning to arrive. At this point,
211 // meta data about the response is available, including for example HTTP
212 // response headers if this is a request for a HTTP resource.
213 virtual void OnResponseStarted(URLRequest* request) = 0;
215 // Called when the a Read of the response body is completed after an
216 // IO_PENDING status from a Read() call.
217 // The data read is filled into the buffer which the caller passed
218 // to Read() previously.
220 // If an error occurred, request->status() will contain the error,
221 // and bytes read will be -1.
222 virtual void OnReadCompleted(URLRequest* request, int bytes_read) = 0;
224 protected:
225 virtual ~Delegate() {}
228 // If destroyed after Start() has been called but while IO is pending,
229 // then the request will be effectively canceled and the delegate
230 // will not have any more of its methods called.
231 ~URLRequest() override;
233 // Changes the default cookie policy from allowing all cookies to blocking all
234 // cookies. Embedders that want to implement a more flexible policy should
235 // change the default to blocking all cookies, and provide a NetworkDelegate
236 // with the URLRequestContext that maintains the CookieStore.
237 // The cookie policy default has to be set before the first URLRequest is
238 // started. Once it was set to block all cookies, it cannot be changed back.
239 static void SetDefaultCookiePolicyToBlock();
241 // Returns true if the scheme can be handled by URLRequest. False otherwise.
242 static bool IsHandledProtocol(const std::string& scheme);
244 // Returns true if the url can be handled by URLRequest. False otherwise.
245 // The function returns true for invalid urls because URLRequest knows how
246 // to handle those.
247 // NOTE: This will also return true for URLs that are handled by
248 // ProtocolFactories that only work for requests that are scoped to a
249 // Profile.
250 static bool IsHandledURL(const GURL& url);
252 // The original url is the url used to initialize the request, and it may
253 // differ from the url if the request was redirected.
254 const GURL& original_url() const { return url_chain_.front(); }
255 // The chain of urls traversed by this request. If the request had no
256 // redirects, this vector will contain one element.
257 const std::vector<GURL>& url_chain() const { return url_chain_; }
258 const GURL& url() const { return url_chain_.back(); }
260 // The URL that should be consulted for the third-party cookie blocking
261 // policy.
263 // WARNING: This URL must only be used for the third-party cookie blocking
264 // policy. It MUST NEVER be used for any kind of SECURITY check.
266 // For example, if a top-level navigation is redirected, the
267 // first-party for cookies will be the URL of the first URL in the
268 // redirect chain throughout the whole redirect. If it was used for
269 // a security check, an attacker might try to get around this check
270 // by starting from some page that redirects to the
271 // host-to-be-attacked.
272 const GURL& first_party_for_cookies() const {
273 return first_party_for_cookies_;
275 // This method may only be called before Start().
276 void set_first_party_for_cookies(const GURL& first_party_for_cookies);
278 // The first-party URL policy to apply when updating the first party URL
279 // during redirects. The first-party URL policy may only be changed before
280 // Start() is called.
281 FirstPartyURLPolicy first_party_url_policy() const {
282 return first_party_url_policy_;
284 void set_first_party_url_policy(FirstPartyURLPolicy first_party_url_policy);
286 // The request method, as an uppercase string. "GET" is the default value.
287 // The request method may only be changed before Start() is called and
288 // should only be assigned an uppercase value.
289 const std::string& method() const { return method_; }
290 void set_method(const std::string& method);
292 // Determines the new method of the request afer following a redirect.
293 // |method| is the method used to arrive at the redirect,
294 // |http_status_code| is the status code associated with the redirect.
295 static std::string ComputeMethodForRedirect(const std::string& method,
296 int http_status_code);
298 // The referrer URL for the request. This header may actually be suppressed
299 // from the underlying network request for security reasons (e.g., a HTTPS
300 // URL will not be sent as the referrer for a HTTP request). The referrer
301 // may only be changed before Start() is called.
302 const std::string& referrer() const { return referrer_; }
303 // Referrer is sanitized to remove URL fragment, user name and password.
304 void SetReferrer(const std::string& referrer);
306 // The referrer policy to apply when updating the referrer during redirects.
307 // The referrer policy may only be changed before Start() is called.
308 ReferrerPolicy referrer_policy() const { return referrer_policy_; }
309 void set_referrer_policy(ReferrerPolicy referrer_policy);
311 // Sets the delegate of the request. This value may be changed at any time,
312 // and it is permissible for it to be null.
313 void set_delegate(Delegate* delegate);
315 // Indicates that the request body should be sent using chunked transfer
316 // encoding. This method may only be called before Start() is called.
317 void EnableChunkedUpload();
319 // Appends the given bytes to the request's upload data to be sent
320 // immediately via chunked transfer encoding. When all data has been sent,
321 // call MarkEndOfChunks() to indicate the end of upload data.
323 // This method may be called only after calling EnableChunkedUpload().
324 void AppendChunkToUpload(const char* bytes,
325 int bytes_len,
326 bool is_last_chunk);
328 // Sets the upload data.
329 void set_upload(scoped_ptr<UploadDataStream> upload);
331 // Gets the upload data.
332 const UploadDataStream* get_upload() const;
334 // Returns true if the request has a non-empty message body to upload.
335 bool has_upload() const;
337 // Set an extra request header by ID or name, or remove one by name. These
338 // methods may only be called before Start() is called, or before a new
339 // redirect in the request chain.
340 void SetExtraRequestHeaderById(int header_id, const std::string& value,
341 bool overwrite);
342 void SetExtraRequestHeaderByName(const std::string& name,
343 const std::string& value, bool overwrite);
344 void RemoveRequestHeaderByName(const std::string& name);
346 // Sets all extra request headers. Any extra request headers set by other
347 // methods are overwritten by this method. This method may only be called
348 // before Start() is called. It is an error to call it later.
349 void SetExtraRequestHeaders(const HttpRequestHeaders& headers);
351 const HttpRequestHeaders& extra_request_headers() const {
352 return extra_request_headers_;
355 // Gets the full request headers sent to the server.
357 // Return true and overwrites headers if it can get the request headers;
358 // otherwise, returns false and does not modify headers. (Always returns
359 // false for request types that don't have headers, like file requests.)
361 // This is guaranteed to succeed if:
363 // 1. A redirect or auth callback is currently running. Once it ends, the
364 // headers may become unavailable as a new request with the new address
365 // or credentials is made.
367 // 2. The OnResponseStarted callback is currently running or has run.
368 bool GetFullRequestHeaders(HttpRequestHeaders* headers) const;
370 // Gets the total amount of data received from network after SSL decoding and
371 // proxy handling.
372 int64 GetTotalReceivedBytes() const;
374 // Returns the current load state for the request. The returned value's
375 // |param| field is an optional parameter describing details related to the
376 // load state. Not all load states have a parameter.
377 LoadStateWithParam GetLoadState() const;
379 // Returns a partial representation of the request's state as a value, for
380 // debugging. Caller takes ownership of returned value.
381 base::Value* GetStateAsValue() const;
383 // Logs information about the what external object currently blocking the
384 // request. LogUnblocked must be called before resuming the request. This
385 // can be called multiple times in a row either with or without calling
386 // LogUnblocked between calls. |blocked_by| must not be NULL or have length
387 // 0.
388 void LogBlockedBy(const char* blocked_by);
390 // Just like LogBlockedBy, but also makes GetLoadState return source as the
391 // |param| in the value returned by GetLoadState. Calling LogUnblocked or
392 // LogBlockedBy will clear the load param. |blocked_by| must not be NULL or
393 // have length 0.
394 void LogAndReportBlockedBy(const char* blocked_by);
396 // Logs that the request is no longer blocked by the last caller to
397 // LogBlockedBy.
398 void LogUnblocked();
400 // Returns the current upload progress in bytes. When the upload data is
401 // chunked, size is set to zero, but position will not be.
402 UploadProgress GetUploadProgress() const;
404 // Get response header(s) by ID or name. These methods may only be called
405 // once the delegate's OnResponseStarted method has been called. Headers
406 // that appear more than once in the response are coalesced, with values
407 // separated by commas (per RFC 2616). This will not work with cookies since
408 // comma can be used in cookie values.
409 // TODO(darin): add API to enumerate response headers.
410 void GetResponseHeaderById(int header_id, std::string* value);
411 void GetResponseHeaderByName(const std::string& name, std::string* value);
413 // Get all response headers, \n-delimited and \n\0-terminated. This includes
414 // the response status line. Restrictions on GetResponseHeaders apply.
415 void GetAllResponseHeaders(std::string* headers);
417 // The time when |this| was constructed.
418 base::TimeTicks creation_time() const { return creation_time_; }
420 // The time at which the returned response was requested. For cached
421 // responses, this is the last time the cache entry was validated.
422 const base::Time& request_time() const {
423 return response_info_.request_time;
426 // The time at which the returned response was generated. For cached
427 // responses, this is the last time the cache entry was validated.
428 const base::Time& response_time() const {
429 return response_info_.response_time;
432 // Indicate if this response was fetched from disk cache.
433 bool was_cached() const { return response_info_.was_cached; }
435 // Returns true if the URLRequest was delivered through a proxy.
436 bool was_fetched_via_proxy() const {
437 return response_info_.was_fetched_via_proxy;
440 // Returns true if the URLRequest was delivered over SPDY.
441 bool was_fetched_via_spdy() const {
442 return response_info_.was_fetched_via_spdy;
445 // Returns the host and port that the content was fetched from. See
446 // http_response_info.h for caveats relating to cached content.
447 HostPortPair GetSocketAddress() const;
449 // Get all response headers, as a HttpResponseHeaders object. See comments
450 // in HttpResponseHeaders class as to the format of the data.
451 HttpResponseHeaders* response_headers() const;
453 // Get the SSL connection info.
454 const SSLInfo& ssl_info() const {
455 return response_info_.ssl_info;
458 // Gets timing information related to the request. Events that have not yet
459 // occurred are left uninitialized. After a second request starts, due to
460 // a redirect or authentication, values will be reset.
462 // LoadTimingInfo only contains ConnectTiming information and socket IDs for
463 // non-cached HTTP responses.
464 void GetLoadTimingInfo(LoadTimingInfo* load_timing_info) const;
466 // Returns the cookie values included in the response, if the request is one
467 // that can have cookies. Returns true if the request is a cookie-bearing
468 // type, false otherwise. This method may only be called once the
469 // delegate's OnResponseStarted method has been called.
470 bool GetResponseCookies(ResponseCookies* cookies);
472 // Get the mime type. This method may only be called once the delegate's
473 // OnResponseStarted method has been called.
474 void GetMimeType(std::string* mime_type) const;
476 // Get the charset (character encoding). This method may only be called once
477 // the delegate's OnResponseStarted method has been called.
478 void GetCharset(std::string* charset) const;
480 // Returns the HTTP response code (e.g., 200, 404, and so on). This method
481 // may only be called once the delegate's OnResponseStarted method has been
482 // called. For non-HTTP requests, this method returns -1.
483 int GetResponseCode() const;
485 // Get the HTTP response info in its entirety.
486 const HttpResponseInfo& response_info() const { return response_info_; }
488 // Access the LOAD_* flags modifying this request (see load_flags.h).
489 int load_flags() const { return load_flags_; }
491 // The new flags may change the IGNORE_LIMITS flag only when called
492 // before Start() is called, it must only set the flag, and if set,
493 // the priority of this request must already be MAXIMUM_PRIORITY.
494 void SetLoadFlags(int flags);
496 // Returns true if the request is "pending" (i.e., if Start() has been called,
497 // and the response has not yet been called).
498 bool is_pending() const { return is_pending_; }
500 // Returns true if the request is in the process of redirecting to a new
501 // URL but has not yet initiated the new request.
502 bool is_redirecting() const { return is_redirecting_; }
504 // Returns the error status of the request.
505 const URLRequestStatus& status() const { return status_; }
507 // Returns a globally unique identifier for this request.
508 uint64 identifier() const { return identifier_; }
510 // This method is called to start the request. The delegate will receive
511 // a OnResponseStarted callback when the request is started.
512 void Start();
514 // This method may be called at any time after Start() has been called to
515 // cancel the request. This method may be called many times, and it has
516 // no effect once the response has completed. It is guaranteed that no
517 // methods of the delegate will be called after the request has been
518 // cancelled, except that this may call the delegate's OnReadCompleted()
519 // during the call to Cancel itself.
520 void Cancel();
522 // Cancels the request and sets the error to |error| (see net_error_list.h
523 // for values).
524 void CancelWithError(int error);
526 // Cancels the request and sets the error to |error| (see net_error_list.h
527 // for values) and attaches |ssl_info| as the SSLInfo for that request. This
528 // is useful to attach a certificate and certificate error to a canceled
529 // request.
530 void CancelWithSSLError(int error, const SSLInfo& ssl_info);
532 // Read initiates an asynchronous read from the response, and must only
533 // be called after the OnResponseStarted callback is received with a
534 // successful status.
535 // If data is available, Read will return true, and the data and length will
536 // be returned immediately. If data is not available, Read returns false,
537 // and an asynchronous Read is initiated. The Read is finished when
538 // the caller receives the OnReadComplete callback. Unless the request was
539 // cancelled, OnReadComplete will always be called, even if the read failed.
541 // The buf parameter is a buffer to receive the data. If the operation
542 // completes asynchronously, the implementation will reference the buffer
543 // until OnReadComplete is called. The buffer must be at least max_bytes in
544 // length.
546 // The max_bytes parameter is the maximum number of bytes to read.
548 // The bytes_read parameter is an output parameter containing the
549 // the number of bytes read. A value of 0 indicates that there is no
550 // more data available to read from the stream.
552 // If a read error occurs, Read returns false and the request->status
553 // will be set to an error.
554 bool Read(IOBuffer* buf, int max_bytes, int* bytes_read);
556 // If this request is being cached by the HTTP cache, stop subsequent caching.
557 // Note that this method has no effect on other (simultaneous or not) requests
558 // for the same resource. The typical example is a request that results in
559 // the data being stored to disk (downloaded instead of rendered) so we don't
560 // want to store it twice.
561 void StopCaching();
563 // This method may be called to follow a redirect that was deferred in
564 // response to an OnReceivedRedirect call.
565 void FollowDeferredRedirect();
567 // This method must be called to resume network communications that were
568 // deferred in response to an OnBeforeNetworkStart call.
569 void ResumeNetworkStart();
571 // One of the following two methods should be called in response to an
572 // OnAuthRequired() callback (and only then).
573 // SetAuth will reissue the request with the given credentials.
574 // CancelAuth will give up and display the error page.
575 void SetAuth(const AuthCredentials& credentials);
576 void CancelAuth();
578 // This method can be called after the user selects a client certificate to
579 // instruct this URLRequest to continue with the request with the
580 // certificate. Pass NULL if the user doesn't have a client certificate.
581 void ContinueWithCertificate(X509Certificate* client_cert);
583 // This method can be called after some error notifications to instruct this
584 // URLRequest to ignore the current error and continue with the request. To
585 // cancel the request instead, call Cancel().
586 void ContinueDespiteLastError();
588 // Used to specify the context (cookie store, cache) for this request.
589 const URLRequestContext* context() const;
591 const BoundNetLog& net_log() const { return net_log_; }
593 // Returns the expected content size if available
594 int64 GetExpectedContentSize() const;
596 // Returns the priority level for this request.
597 RequestPriority priority() const { return priority_; }
599 // Sets the priority level for this request and any related
600 // jobs. Must not change the priority to anything other than
601 // MAXIMUM_PRIORITY if the IGNORE_LIMITS load flag is set.
602 void SetPriority(RequestPriority priority);
604 // Returns true iff this request would be internally redirected to HTTPS
605 // due to HSTS. If so, |redirect_url| is rewritten to the new HTTPS URL.
606 bool GetHSTSRedirect(GURL* redirect_url) const;
608 // TODO(willchan): Undo this. Only temporarily public.
609 bool has_delegate() const { return delegate_ != NULL; }
611 // NOTE(willchan): This is just temporary for debugging
612 // http://crbug.com/90971.
613 // Allows to setting debug info into the URLRequest.
614 void set_stack_trace(const base::debug::StackTrace& stack_trace);
615 const base::debug::StackTrace* stack_trace() const;
617 void set_received_response_content_length(int64 received_content_length) {
618 received_response_content_length_ = received_content_length;
620 int64 received_response_content_length() const {
621 return received_response_content_length_;
624 // Available at NetworkDelegate::NotifyHeadersReceived() time, which is before
625 // the more general response_info() is available, even though it is a subset.
626 const HostPortPair& proxy_server() const {
627 return proxy_server_;
630 protected:
631 // Allow the URLRequestJob class to control the is_pending() flag.
632 void set_is_pending(bool value) { is_pending_ = value; }
634 // Allow the URLRequestJob class to set our status too
635 void set_status(const URLRequestStatus& value) { status_ = value; }
637 CookieStore* cookie_store() const { return cookie_store_.get(); }
639 // Allow the URLRequestJob to redirect this request. Returns OK if
640 // successful, otherwise an error code is returned.
641 int Redirect(const RedirectInfo& redirect_info);
643 // Called by URLRequestJob to allow interception when a redirect occurs.
644 void NotifyReceivedRedirect(const RedirectInfo& redirect_info,
645 bool* defer_redirect);
647 // Called by URLRequestHttpJob (note, only HTTP(S) jobs will call this) to
648 // allow deferral of network initialization.
649 void NotifyBeforeNetworkStart(bool* defer);
651 // Allow an interceptor's URLRequestJob to restart this request.
652 // Should only be called if the original job has not started a response.
653 void Restart();
655 private:
656 friend class URLRequestJob;
657 friend class URLRequestContext;
659 // URLRequests are always created by calling URLRequestContext::CreateRequest.
661 // If no cookie store or network delegate are passed in, will use the ones
662 // from the URLRequestContext.
663 URLRequest(const GURL& url,
664 RequestPriority priority,
665 Delegate* delegate,
666 const URLRequestContext* context,
667 CookieStore* cookie_store,
668 NetworkDelegate* network_delegate);
670 // Resumes or blocks a request paused by the NetworkDelegate::OnBeforeRequest
671 // handler. If |blocked| is true, the request is blocked and an error page is
672 // returned indicating so. This should only be called after Start is called
673 // and OnBeforeRequest returns true (signalling that the request should be
674 // paused).
675 void BeforeRequestComplete(int error);
677 void StartJob(URLRequestJob* job);
679 // Restarting involves replacing the current job with a new one such as what
680 // happens when following a HTTP redirect.
681 void RestartWithJob(URLRequestJob* job);
682 void PrepareToRestart();
684 // Detaches the job from this request in preparation for this object going
685 // away or the job being replaced. The job will not call us back when it has
686 // been orphaned.
687 void OrphanJob();
689 // Cancels the request and set the error and ssl info for this request to the
690 // passed values.
691 void DoCancel(int error, const SSLInfo& ssl_info);
693 // Called by the URLRequestJob when the headers are received, before any other
694 // method, to allow caching of load timing information.
695 void OnHeadersComplete();
697 // Notifies the network delegate that the request has been completed.
698 // This does not imply a successful completion. Also a canceled request is
699 // considered completed.
700 void NotifyRequestCompleted();
702 // Called by URLRequestJob to allow interception when the final response
703 // occurs.
704 void NotifyResponseStarted();
706 // These functions delegate to |delegate_| and may only be used if
707 // |delegate_| is not NULL. See URLRequest::Delegate for the meaning
708 // of these functions.
709 void NotifyAuthRequired(AuthChallengeInfo* auth_info);
710 void NotifyAuthRequiredComplete(NetworkDelegate::AuthRequiredResponse result);
711 void NotifyCertificateRequested(SSLCertRequestInfo* cert_request_info);
712 void NotifySSLCertificateError(const SSLInfo& ssl_info, bool fatal);
713 void NotifyReadCompleted(int bytes_read);
715 // These functions delegate to |network_delegate_| if it is not NULL.
716 // If |network_delegate_| is NULL, cookies can be used unless
717 // SetDefaultCookiePolicyToBlock() has been called.
718 bool CanGetCookies(const CookieList& cookie_list) const;
719 bool CanSetCookie(const std::string& cookie_line,
720 CookieOptions* options) const;
721 bool CanEnablePrivacyMode() const;
723 // Called just before calling a delegate that may block a request.
724 void OnCallToDelegate();
725 // Called when the delegate lets a request continue. Also called on
726 // cancellation.
727 void OnCallToDelegateComplete();
729 // Contextual information used for this request. Cannot be NULL. This contains
730 // most of the dependencies which are shared between requests (disk cache,
731 // cookie store, socket pool, etc.)
732 const URLRequestContext* context_;
734 NetworkDelegate* network_delegate_;
736 // Tracks the time spent in various load states throughout this request.
737 BoundNetLog net_log_;
739 scoped_refptr<URLRequestJob> job_;
740 scoped_ptr<UploadDataStream> upload_data_stream_;
741 // TODO(mmenke): Make whether or not an upload is chunked transparent to the
742 // URLRequest.
743 ChunkedUploadDataStream* upload_chunked_data_stream_;
745 std::vector<GURL> url_chain_;
746 GURL first_party_for_cookies_;
747 GURL delegate_redirect_url_;
748 std::string method_; // "GET", "POST", etc. Should be all uppercase.
749 std::string referrer_;
750 ReferrerPolicy referrer_policy_;
751 FirstPartyURLPolicy first_party_url_policy_;
752 HttpRequestHeaders extra_request_headers_;
753 int load_flags_; // Flags indicating the request type for the load;
754 // expected values are LOAD_* enums above.
756 // Never access methods of the |delegate_| directly. Always use the
757 // Notify... methods for this.
758 Delegate* delegate_;
760 // Current error status of the job. When no error has been encountered, this
761 // will be SUCCESS. If multiple errors have been encountered, this will be
762 // the first non-SUCCESS status seen.
763 URLRequestStatus status_;
765 // The HTTP response info, lazily initialized.
766 HttpResponseInfo response_info_;
768 // Tells us whether the job is outstanding. This is true from the time
769 // Start() is called to the time we dispatch RequestComplete and indicates
770 // whether the job is active.
771 bool is_pending_;
773 // Indicates if the request is in the process of redirecting to a new
774 // location. It is true from the time the headers complete until a
775 // new request begins.
776 bool is_redirecting_;
778 // Number of times we're willing to redirect. Used to guard against
779 // infinite redirects.
780 int redirect_limit_;
782 // Cached value for use after we've orphaned the job handling the
783 // first transaction in a request involving redirects.
784 UploadProgress final_upload_progress_;
786 // The priority level for this request. Objects like
787 // ClientSocketPool use this to determine which URLRequest to
788 // allocate sockets to first.
789 RequestPriority priority_;
791 // TODO(battre): The only consumer of the identifier_ is currently the
792 // web request API. We need to match identifiers of requests between the
793 // web request API and the web navigation API. As the URLRequest does not
794 // exist when the web navigation API is triggered, the tracking probably
795 // needs to be done outside of the URLRequest anyway. Therefore, this
796 // identifier should be deleted here. http://crbug.com/89321
797 // A globally unique identifier for this request.
798 const uint64 identifier_;
800 // True if this request is currently calling a delegate, or is blocked waiting
801 // for the URL request or network delegate to resume it.
802 bool calling_delegate_;
804 // An optional parameter that provides additional information about what
805 // |this| is currently being blocked by.
806 std::string blocked_by_;
807 bool use_blocked_by_as_load_param_;
809 base::debug::LeakTracker<URLRequest> leak_tracker_;
811 // Callback passed to the network delegate to notify us when a blocked request
812 // is ready to be resumed or canceled.
813 CompletionCallback before_request_callback_;
815 // Safe-guard to ensure that we do not send multiple "I am completed"
816 // messages to network delegate.
817 // TODO(battre): Remove this. http://crbug.com/89049
818 bool has_notified_completion_;
820 // Authentication data used by the NetworkDelegate for this request,
821 // if one is present. |auth_credentials_| may be filled in when calling
822 // |NotifyAuthRequired| on the NetworkDelegate. |auth_info_| holds
823 // the authentication challenge being handled by |NotifyAuthRequired|.
824 AuthCredentials auth_credentials_;
825 scoped_refptr<AuthChallengeInfo> auth_info_;
827 int64 received_response_content_length_;
829 base::TimeTicks creation_time_;
831 // Timing information for the most recent request. Its start times are
832 // populated during Start(), and the rest are populated in OnResponseReceived.
833 LoadTimingInfo load_timing_info_;
835 scoped_ptr<const base::debug::StackTrace> stack_trace_;
837 // Keeps track of whether or not OnBeforeNetworkStart has been called yet.
838 bool notified_before_network_start_;
840 // The cookie store to be used for this request.
841 scoped_refptr<CookieStore> cookie_store_;
843 // The proxy server used for this request, if any.
844 HostPortPair proxy_server_;
846 DISALLOW_COPY_AND_ASSIGN(URLRequest);
849 } // namespace net
851 #endif // NET_URL_REQUEST_URL_REQUEST_H_