Add --output-dir flag for page_runner.py to specify a custom directory for
[chromium-blink-merge.git] / net / url_request / url_request.h
blobd8df8fe0c4ccbc5dbce372253783f5438524f785
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 // Temporary layering violation to allow existing users of a deprecated
44 // interface.
45 namespace content {
46 class AppCacheInterceptor;
49 namespace net {
51 class CookieOptions;
52 class HostPortPair;
53 class IOBuffer;
54 struct LoadTimingInfo;
55 struct RedirectInfo;
56 class SSLCertRequestInfo;
57 class SSLInfo;
58 class UploadDataStream;
59 class URLRequestContext;
60 class URLRequestJob;
61 class X509Certificate;
63 // This stores the values of the Set-Cookie headers received during the request.
64 // Each item in the vector corresponds to a Set-Cookie: line received,
65 // excluding the "Set-Cookie:" part.
66 typedef std::vector<std::string> ResponseCookies;
68 //-----------------------------------------------------------------------------
69 // A class representing the asynchronous load of a data stream from an URL.
71 // The lifetime of an instance of this class is completely controlled by the
72 // consumer, and the instance is not required to live on the heap or be
73 // allocated in any special way. It is also valid to delete an URLRequest
74 // object during the handling of a callback to its delegate. Of course, once
75 // the URLRequest is deleted, no further callbacks to its delegate will occur.
77 // NOTE: All usage of all instances of this class should be on the same thread.
79 class NET_EXPORT URLRequest : NON_EXPORTED_BASE(public base::NonThreadSafe),
80 public base::SupportsUserData {
81 public:
82 // Callback function implemented by protocol handlers to create new jobs.
83 // The factory may return NULL to indicate an error, which will cause other
84 // factories to be queried. If no factory handles the request, then the
85 // default job will be used.
86 typedef URLRequestJob* (ProtocolFactory)(URLRequest* request,
87 NetworkDelegate* network_delegate,
88 const std::string& scheme);
90 // HTTP request/response header IDs (via some preprocessor fun) for use with
91 // SetRequestHeaderById and GetResponseHeaderById.
92 enum {
93 #define HTTP_ATOM(x) HTTP_ ## x,
94 #include "net/http/http_atom_list.h"
95 #undef HTTP_ATOM
98 // Referrer policies (see set_referrer_policy): During server redirects, the
99 // referrer header might be cleared, if the protocol changes from HTTPS to
100 // HTTP. This is the default behavior of URLRequest, corresponding to
101 // CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE. Alternatively, the
102 // referrer policy can be set to never change the referrer header. This
103 // behavior corresponds to NEVER_CLEAR_REFERRER. Embedders will want to use
104 // NEVER_CLEAR_REFERRER when implementing the meta-referrer support
105 // (http://wiki.whatwg.org/wiki/Meta_referrer) and sending requests with a
106 // non-default referrer policy. Only the default referrer policy requires
107 // the referrer to be cleared on transitions from HTTPS to HTTP.
108 enum ReferrerPolicy {
109 CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
110 NEVER_CLEAR_REFERRER,
113 // First-party URL redirect policy: During server redirects, the first-party
114 // URL for cookies normally doesn't change. However, if the request is a
115 // top-level first-party request, the first-party URL should be updated to the
116 // URL on every redirect.
117 enum FirstPartyURLPolicy {
118 NEVER_CHANGE_FIRST_PARTY_URL,
119 UPDATE_FIRST_PARTY_URL_ON_REDIRECT,
122 // This class handles network interception. Use with
123 // (Un)RegisterRequestInterceptor.
124 class NET_EXPORT Interceptor {
125 public:
126 virtual ~Interceptor() {}
128 // Called for every request made. Should return a new job to handle the
129 // request if it should be intercepted, or NULL to allow the request to
130 // be handled in the normal manner.
131 virtual URLRequestJob* MaybeIntercept(
132 URLRequest* request, NetworkDelegate* network_delegate) = 0;
134 // Called after having received a redirect response, but prior to the
135 // the request delegate being informed of the redirect. Can return a new
136 // job to replace the existing job if it should be intercepted, or NULL
137 // to allow the normal handling to continue. If a new job is provided,
138 // the delegate never sees the original redirect response, instead the
139 // response produced by the intercept job will be returned.
140 virtual URLRequestJob* MaybeInterceptRedirect(
141 URLRequest* request,
142 NetworkDelegate* network_delegate,
143 const GURL& location);
145 // Called after having received a final response, but prior to the
146 // the request delegate being informed of the response. This is also
147 // called when there is no server response at all to allow interception
148 // on dns or network errors. Can return a new job to replace the existing
149 // job if it should be intercepted, or NULL to allow the normal handling to
150 // continue. If a new job is provided, the delegate never sees the original
151 // response, instead the response produced by the intercept job will be
152 // returned.
153 virtual URLRequestJob* MaybeInterceptResponse(
154 URLRequest* request, NetworkDelegate* network_delegate);
157 // Deprecated interfaces in net::URLRequest. They have been moved to
158 // URLRequest's private section to prevent new uses. Existing uses are
159 // explicitly friended here and should be removed over time.
160 class NET_EXPORT Deprecated {
161 private:
162 // TODO(willchan): Kill off these friend declarations.
163 friend class TestInterceptor;
164 friend class content::AppCacheInterceptor;
166 // TODO(pauljensen): Remove this when AppCacheInterceptor is a
167 // ProtocolHandler, see crbug.com/161547.
168 static void RegisterRequestInterceptor(Interceptor* interceptor);
169 static void UnregisterRequestInterceptor(Interceptor* interceptor);
171 DISALLOW_IMPLICIT_CONSTRUCTORS(Deprecated);
174 // The delegate's methods are called from the message loop of the thread
175 // on which the request's Start() method is called. See above for the
176 // ordering of callbacks.
178 // The callbacks will be called in the following order:
179 // Start()
180 // - OnCertificateRequested* (zero or more calls, if the SSL server and/or
181 // SSL proxy requests a client certificate for authentication)
182 // - OnSSLCertificateError* (zero or one call, if the SSL server's
183 // certificate has an error)
184 // - OnReceivedRedirect* (zero or more calls, for the number of redirects)
185 // - OnAuthRequired* (zero or more calls, for the number of
186 // authentication failures)
187 // - OnResponseStarted
188 // Read() initiated by delegate
189 // - OnReadCompleted* (zero or more calls until all data is read)
191 // Read() must be called at least once. Read() returns true when it completed
192 // immediately, and false if an IO is pending or if there is an error. When
193 // Read() returns false, the caller can check the Request's status() to see
194 // if an error occurred, or if the IO is just pending. When Read() returns
195 // true with zero bytes read, it indicates the end of the response.
197 class NET_EXPORT Delegate {
198 public:
199 // Called upon receiving a redirect. The delegate may call the request's
200 // Cancel method to prevent the redirect from being followed. Since there
201 // may be multiple chained redirects, there may also be more than one
202 // redirect call.
204 // When this function is called, the request will still contain the
205 // original URL, the destination of the redirect is provided in 'new_url'.
206 // If the delegate does not cancel the request and |*defer_redirect| is
207 // false, then the redirect will be followed, and the request's URL will be
208 // changed to the new URL. Otherwise if the delegate does not cancel the
209 // request and |*defer_redirect| is true, then the redirect will be
210 // followed once FollowDeferredRedirect is called on the URLRequest.
212 // The caller must set |*defer_redirect| to false, so that delegates do not
213 // need to set it if they are happy with the default behavior of not
214 // deferring redirect.
215 virtual void OnReceivedRedirect(URLRequest* request,
216 const RedirectInfo& redirect_info,
217 bool* defer_redirect);
219 // Called when we receive an authentication failure. The delegate should
220 // call request->SetAuth() with the user's credentials once it obtains them,
221 // or request->CancelAuth() to cancel the login and display the error page.
222 // When it does so, the request will be reissued, restarting the sequence
223 // of On* callbacks.
224 virtual void OnAuthRequired(URLRequest* request,
225 AuthChallengeInfo* auth_info);
227 // Called when we receive an SSL CertificateRequest message for client
228 // authentication. The delegate should call
229 // request->ContinueWithCertificate() with the client certificate the user
230 // selected, or request->ContinueWithCertificate(NULL) to continue the SSL
231 // handshake without a client certificate.
232 virtual void OnCertificateRequested(
233 URLRequest* request,
234 SSLCertRequestInfo* cert_request_info);
236 // Called when using SSL and the server responds with a certificate with
237 // an error, for example, whose common name does not match the common name
238 // we were expecting for that host. The delegate should either do the
239 // safe thing and Cancel() the request or decide to proceed by calling
240 // ContinueDespiteLastError(). cert_error is a ERR_* error code
241 // indicating what's wrong with the certificate.
242 // If |fatal| is true then the host in question demands a higher level
243 // of security (due e.g. to HTTP Strict Transport Security, user
244 // preference, or built-in policy). In this case, errors must not be
245 // bypassable by the user.
246 virtual void OnSSLCertificateError(URLRequest* request,
247 const SSLInfo& ssl_info,
248 bool fatal);
250 // Called to notify that the request must use the network to complete the
251 // request and is about to do so. This is called at most once per
252 // URLRequest, and by default does not defer. If deferred, call
253 // ResumeNetworkStart() to continue or Cancel() to cancel.
254 virtual void OnBeforeNetworkStart(URLRequest* request, bool* defer);
256 // After calling Start(), the delegate will receive an OnResponseStarted
257 // callback when the request has completed. If an error occurred, the
258 // request->status() will be set. On success, all redirects have been
259 // followed and the final response is beginning to arrive. At this point,
260 // meta data about the response is available, including for example HTTP
261 // response headers if this is a request for a HTTP resource.
262 virtual void OnResponseStarted(URLRequest* request) = 0;
264 // Called when the a Read of the response body is completed after an
265 // IO_PENDING status from a Read() call.
266 // The data read is filled into the buffer which the caller passed
267 // to Read() previously.
269 // If an error occurred, request->status() will contain the error,
270 // and bytes read will be -1.
271 virtual void OnReadCompleted(URLRequest* request, int bytes_read) = 0;
273 protected:
274 virtual ~Delegate() {}
277 // If destroyed after Start() has been called but while IO is pending,
278 // then the request will be effectively canceled and the delegate
279 // will not have any more of its methods called.
280 virtual ~URLRequest();
282 // Changes the default cookie policy from allowing all cookies to blocking all
283 // cookies. Embedders that want to implement a more flexible policy should
284 // change the default to blocking all cookies, and provide a NetworkDelegate
285 // with the URLRequestContext that maintains the CookieStore.
286 // The cookie policy default has to be set before the first URLRequest is
287 // started. Once it was set to block all cookies, it cannot be changed back.
288 static void SetDefaultCookiePolicyToBlock();
290 // Returns true if the scheme can be handled by URLRequest. False otherwise.
291 static bool IsHandledProtocol(const std::string& scheme);
293 // Returns true if the url can be handled by URLRequest. False otherwise.
294 // The function returns true for invalid urls because URLRequest knows how
295 // to handle those.
296 // NOTE: This will also return true for URLs that are handled by
297 // ProtocolFactories that only work for requests that are scoped to a
298 // Profile.
299 static bool IsHandledURL(const GURL& url);
301 // The original url is the url used to initialize the request, and it may
302 // differ from the url if the request was redirected.
303 const GURL& original_url() const { return url_chain_.front(); }
304 // The chain of urls traversed by this request. If the request had no
305 // redirects, this vector will contain one element.
306 const std::vector<GURL>& url_chain() const { return url_chain_; }
307 const GURL& url() const { return url_chain_.back(); }
309 // The URL that should be consulted for the third-party cookie blocking
310 // policy.
312 // WARNING: This URL must only be used for the third-party cookie blocking
313 // policy. It MUST NEVER be used for any kind of SECURITY check.
315 // For example, if a top-level navigation is redirected, the
316 // first-party for cookies will be the URL of the first URL in the
317 // redirect chain throughout the whole redirect. If it was used for
318 // a security check, an attacker might try to get around this check
319 // by starting from some page that redirects to the
320 // host-to-be-attacked.
321 const GURL& first_party_for_cookies() const {
322 return first_party_for_cookies_;
324 // This method may only be called before Start().
325 void set_first_party_for_cookies(const GURL& first_party_for_cookies);
327 // The first-party URL policy to apply when updating the first party URL
328 // during redirects. The first-party URL policy may only be changed before
329 // Start() is called.
330 FirstPartyURLPolicy first_party_url_policy() const {
331 return first_party_url_policy_;
333 void set_first_party_url_policy(FirstPartyURLPolicy first_party_url_policy);
335 // The request method, as an uppercase string. "GET" is the default value.
336 // The request method may only be changed before Start() is called and
337 // should only be assigned an uppercase value.
338 const std::string& method() const { return method_; }
339 void set_method(const std::string& method);
341 // Determines the new method of the request afer following a redirect.
342 // |method| is the method used to arrive at the redirect,
343 // |http_status_code| is the status code associated with the redirect.
344 static std::string ComputeMethodForRedirect(const std::string& method,
345 int http_status_code);
347 // The referrer URL for the request. This header may actually be suppressed
348 // from the underlying network request for security reasons (e.g., a HTTPS
349 // URL will not be sent as the referrer for a HTTP request). The referrer
350 // may only be changed before Start() is called.
351 const std::string& referrer() const { return referrer_; }
352 // Referrer is sanitized to remove URL fragment, user name and password.
353 void SetReferrer(const std::string& referrer);
355 // The referrer policy to apply when updating the referrer during redirects.
356 // The referrer policy may only be changed before Start() is called.
357 ReferrerPolicy referrer_policy() const { return referrer_policy_; }
358 void set_referrer_policy(ReferrerPolicy referrer_policy);
360 // Sets the delegate of the request. This value may be changed at any time,
361 // and it is permissible for it to be null.
362 void set_delegate(Delegate* delegate);
364 // Indicates that the request body should be sent using chunked transfer
365 // encoding. This method may only be called before Start() is called.
366 void EnableChunkedUpload();
368 // Appends the given bytes to the request's upload data to be sent
369 // immediately via chunked transfer encoding. When all data has been sent,
370 // call MarkEndOfChunks() to indicate the end of upload data.
372 // This method may be called only after calling EnableChunkedUpload().
373 void AppendChunkToUpload(const char* bytes,
374 int bytes_len,
375 bool is_last_chunk);
377 // Sets the upload data.
378 void set_upload(scoped_ptr<UploadDataStream> upload);
380 // Gets the upload data.
381 const UploadDataStream* get_upload() const;
383 // Returns true if the request has a non-empty message body to upload.
384 bool has_upload() const;
386 // Set an extra request header by ID or name, or remove one by name. These
387 // methods may only be called before Start() is called, or before a new
388 // redirect in the request chain.
389 void SetExtraRequestHeaderById(int header_id, const std::string& value,
390 bool overwrite);
391 void SetExtraRequestHeaderByName(const std::string& name,
392 const std::string& value, bool overwrite);
393 void RemoveRequestHeaderByName(const std::string& name);
395 // Sets all extra request headers. Any extra request headers set by other
396 // methods are overwritten by this method. This method may only be called
397 // before Start() is called. It is an error to call it later.
398 void SetExtraRequestHeaders(const HttpRequestHeaders& headers);
400 const HttpRequestHeaders& extra_request_headers() const {
401 return extra_request_headers_;
404 // Gets the full request headers sent to the server.
406 // Return true and overwrites headers if it can get the request headers;
407 // otherwise, returns false and does not modify headers. (Always returns
408 // false for request types that don't have headers, like file requests.)
410 // This is guaranteed to succeed if:
412 // 1. A redirect or auth callback is currently running. Once it ends, the
413 // headers may become unavailable as a new request with the new address
414 // or credentials is made.
416 // 2. The OnResponseStarted callback is currently running or has run.
417 bool GetFullRequestHeaders(HttpRequestHeaders* headers) const;
419 // Gets the total amount of data received from network after SSL decoding and
420 // proxy handling.
421 int64 GetTotalReceivedBytes() const;
423 // Returns the current load state for the request. The returned value's
424 // |param| field is an optional parameter describing details related to the
425 // load state. Not all load states have a parameter.
426 LoadStateWithParam GetLoadState() const;
428 // Returns a partial representation of the request's state as a value, for
429 // debugging. Caller takes ownership of returned value.
430 base::Value* GetStateAsValue() const;
432 // Logs information about the what external object currently blocking the
433 // request. LogUnblocked must be called before resuming the request. This
434 // can be called multiple times in a row either with or without calling
435 // LogUnblocked between calls. |blocked_by| must not be NULL or have length
436 // 0.
437 void LogBlockedBy(const char* blocked_by);
439 // Just like LogBlockedBy, but also makes GetLoadState return source as the
440 // |param| in the value returned by GetLoadState. Calling LogUnblocked or
441 // LogBlockedBy will clear the load param. |blocked_by| must not be NULL or
442 // have length 0.
443 void LogAndReportBlockedBy(const char* blocked_by);
445 // Logs that the request is no longer blocked by the last caller to
446 // LogBlockedBy.
447 void LogUnblocked();
449 // Returns the current upload progress in bytes. When the upload data is
450 // chunked, size is set to zero, but position will not be.
451 UploadProgress GetUploadProgress() const;
453 // Get response header(s) by ID or name. These methods may only be called
454 // once the delegate's OnResponseStarted method has been called. Headers
455 // that appear more than once in the response are coalesced, with values
456 // separated by commas (per RFC 2616). This will not work with cookies since
457 // comma can be used in cookie values.
458 // TODO(darin): add API to enumerate response headers.
459 void GetResponseHeaderById(int header_id, std::string* value);
460 void GetResponseHeaderByName(const std::string& name, std::string* value);
462 // Get all response headers, \n-delimited and \n\0-terminated. This includes
463 // the response status line. Restrictions on GetResponseHeaders apply.
464 void GetAllResponseHeaders(std::string* headers);
466 // The time when |this| was constructed.
467 base::TimeTicks creation_time() const { return creation_time_; }
469 // The time at which the returned response was requested. For cached
470 // responses, this is the last time the cache entry was validated.
471 const base::Time& request_time() const {
472 return response_info_.request_time;
475 // The time at which the returned response was generated. For cached
476 // responses, this is the last time the cache entry was validated.
477 const base::Time& response_time() const {
478 return response_info_.response_time;
481 // Indicate if this response was fetched from disk cache.
482 bool was_cached() const { return response_info_.was_cached; }
484 // Returns true if the URLRequest was delivered through a proxy.
485 bool was_fetched_via_proxy() const {
486 return response_info_.was_fetched_via_proxy;
489 // Returns true if the URLRequest was delivered over SPDY.
490 bool was_fetched_via_spdy() const {
491 return response_info_.was_fetched_via_spdy;
494 // Returns the host and port that the content was fetched from. See
495 // http_response_info.h for caveats relating to cached content.
496 HostPortPair GetSocketAddress() const;
498 // Get all response headers, as a HttpResponseHeaders object. See comments
499 // in HttpResponseHeaders class as to the format of the data.
500 HttpResponseHeaders* response_headers() const;
502 // Get the SSL connection info.
503 const SSLInfo& ssl_info() const {
504 return response_info_.ssl_info;
507 // Gets timing information related to the request. Events that have not yet
508 // occurred are left uninitialized. After a second request starts, due to
509 // a redirect or authentication, values will be reset.
511 // LoadTimingInfo only contains ConnectTiming information and socket IDs for
512 // non-cached HTTP responses.
513 void GetLoadTimingInfo(LoadTimingInfo* load_timing_info) const;
515 // Returns the cookie values included in the response, if the request is one
516 // that can have cookies. Returns true if the request is a cookie-bearing
517 // type, false otherwise. This method may only be called once the
518 // delegate's OnResponseStarted method has been called.
519 bool GetResponseCookies(ResponseCookies* cookies);
521 // Get the mime type. This method may only be called once the delegate's
522 // OnResponseStarted method has been called.
523 void GetMimeType(std::string* mime_type) const;
525 // Get the charset (character encoding). This method may only be called once
526 // the delegate's OnResponseStarted method has been called.
527 void GetCharset(std::string* charset) const;
529 // Returns the HTTP response code (e.g., 200, 404, and so on). This method
530 // may only be called once the delegate's OnResponseStarted method has been
531 // called. For non-HTTP requests, this method returns -1.
532 int GetResponseCode() const;
534 // Get the HTTP response info in its entirety.
535 const HttpResponseInfo& response_info() const { return response_info_; }
537 // Access the LOAD_* flags modifying this request (see load_flags.h).
538 int load_flags() const { return load_flags_; }
540 // The new flags may change the IGNORE_LIMITS flag only when called
541 // before Start() is called, it must only set the flag, and if set,
542 // the priority of this request must already be MAXIMUM_PRIORITY.
543 void SetLoadFlags(int flags);
545 // Returns true if the request is "pending" (i.e., if Start() has been called,
546 // and the response has not yet been called).
547 bool is_pending() const { return is_pending_; }
549 // Returns true if the request is in the process of redirecting to a new
550 // URL but has not yet initiated the new request.
551 bool is_redirecting() const { return is_redirecting_; }
553 // Returns the error status of the request.
554 const URLRequestStatus& status() const { return status_; }
556 // Returns a globally unique identifier for this request.
557 uint64 identifier() const { return identifier_; }
559 // This method is called to start the request. The delegate will receive
560 // a OnResponseStarted callback when the request is started.
561 void Start();
563 // This method may be called at any time after Start() has been called to
564 // cancel the request. This method may be called many times, and it has
565 // no effect once the response has completed. It is guaranteed that no
566 // methods of the delegate will be called after the request has been
567 // cancelled, except that this may call the delegate's OnReadCompleted()
568 // during the call to Cancel itself.
569 void Cancel();
571 // Cancels the request and sets the error to |error| (see net_error_list.h
572 // for values).
573 void CancelWithError(int error);
575 // Cancels the request and sets the error to |error| (see net_error_list.h
576 // for values) and attaches |ssl_info| as the SSLInfo for that request. This
577 // is useful to attach a certificate and certificate error to a canceled
578 // request.
579 void CancelWithSSLError(int error, const SSLInfo& ssl_info);
581 // Read initiates an asynchronous read from the response, and must only
582 // be called after the OnResponseStarted callback is received with a
583 // successful status.
584 // If data is available, Read will return true, and the data and length will
585 // be returned immediately. If data is not available, Read returns false,
586 // and an asynchronous Read is initiated. The Read is finished when
587 // the caller receives the OnReadComplete callback. Unless the request was
588 // cancelled, OnReadComplete will always be called, even if the read failed.
590 // The buf parameter is a buffer to receive the data. If the operation
591 // completes asynchronously, the implementation will reference the buffer
592 // until OnReadComplete is called. The buffer must be at least max_bytes in
593 // length.
595 // The max_bytes parameter is the maximum number of bytes to read.
597 // The bytes_read parameter is an output parameter containing the
598 // the number of bytes read. A value of 0 indicates that there is no
599 // more data available to read from the stream.
601 // If a read error occurs, Read returns false and the request->status
602 // will be set to an error.
603 bool Read(IOBuffer* buf, int max_bytes, int* bytes_read);
605 // If this request is being cached by the HTTP cache, stop subsequent caching.
606 // Note that this method has no effect on other (simultaneous or not) requests
607 // for the same resource. The typical example is a request that results in
608 // the data being stored to disk (downloaded instead of rendered) so we don't
609 // want to store it twice.
610 void StopCaching();
612 // This method may be called to follow a redirect that was deferred in
613 // response to an OnReceivedRedirect call.
614 void FollowDeferredRedirect();
616 // This method must be called to resume network communications that were
617 // deferred in response to an OnBeforeNetworkStart call.
618 void ResumeNetworkStart();
620 // One of the following two methods should be called in response to an
621 // OnAuthRequired() callback (and only then).
622 // SetAuth will reissue the request with the given credentials.
623 // CancelAuth will give up and display the error page.
624 void SetAuth(const AuthCredentials& credentials);
625 void CancelAuth();
627 // This method can be called after the user selects a client certificate to
628 // instruct this URLRequest to continue with the request with the
629 // certificate. Pass NULL if the user doesn't have a client certificate.
630 void ContinueWithCertificate(X509Certificate* client_cert);
632 // This method can be called after some error notifications to instruct this
633 // URLRequest to ignore the current error and continue with the request. To
634 // cancel the request instead, call Cancel().
635 void ContinueDespiteLastError();
637 // Used to specify the context (cookie store, cache) for this request.
638 const URLRequestContext* context() const;
640 const BoundNetLog& net_log() const { return net_log_; }
642 // Returns the expected content size if available
643 int64 GetExpectedContentSize() const;
645 // Returns the priority level for this request.
646 RequestPriority priority() const { return priority_; }
648 // Sets the priority level for this request and any related
649 // jobs. Must not change the priority to anything other than
650 // MAXIMUM_PRIORITY if the IGNORE_LIMITS load flag is set.
651 void SetPriority(RequestPriority priority);
653 // Returns true iff this request would be internally redirected to HTTPS
654 // due to HSTS. If so, |redirect_url| is rewritten to the new HTTPS URL.
655 bool GetHSTSRedirect(GURL* redirect_url) const;
657 // TODO(willchan): Undo this. Only temporarily public.
658 bool has_delegate() const { return delegate_ != NULL; }
660 // NOTE(willchan): This is just temporary for debugging
661 // http://crbug.com/90971.
662 // Allows to setting debug info into the URLRequest.
663 void set_stack_trace(const base::debug::StackTrace& stack_trace);
664 const base::debug::StackTrace* stack_trace() const;
666 void set_received_response_content_length(int64 received_content_length) {
667 received_response_content_length_ = received_content_length;
669 int64 received_response_content_length() const {
670 return received_response_content_length_;
673 // Available at NetworkDelegate::NotifyHeadersReceived() time, which is before
674 // the more general response_info() is available, even though it is a subset.
675 const HostPortPair& proxy_server() const {
676 return proxy_server_;
679 protected:
680 // Allow the URLRequestJob class to control the is_pending() flag.
681 void set_is_pending(bool value) { is_pending_ = value; }
683 // Allow the URLRequestJob class to set our status too
684 void set_status(const URLRequestStatus& value) { status_ = value; }
686 CookieStore* cookie_store() const { return cookie_store_.get(); }
688 // Allow the URLRequestJob to redirect this request. Returns OK if
689 // successful, otherwise an error code is returned.
690 int Redirect(const RedirectInfo& redirect_info);
692 // Called by URLRequestJob to allow interception when a redirect occurs.
693 void NotifyReceivedRedirect(const RedirectInfo& redirect_info,
694 bool* defer_redirect);
696 // Called by URLRequestHttpJob (note, only HTTP(S) jobs will call this) to
697 // allow deferral of network initialization.
698 void NotifyBeforeNetworkStart(bool* defer);
700 // Allow an interceptor's URLRequestJob to restart this request.
701 // Should only be called if the original job has not started a response.
702 void Restart();
704 private:
705 friend class URLRequestJob;
706 friend class URLRequestContext;
708 // URLRequests are always created by calling URLRequestContext::CreateRequest.
710 // If no cookie store or network delegate are passed in, will use the ones
711 // from the URLRequestContext.
712 URLRequest(const GURL& url,
713 RequestPriority priority,
714 Delegate* delegate,
715 const URLRequestContext* context,
716 CookieStore* cookie_store,
717 NetworkDelegate* network_delegate);
719 // Registers or unregisters a network interception class.
720 static void RegisterRequestInterceptor(Interceptor* interceptor);
721 static void UnregisterRequestInterceptor(Interceptor* interceptor);
723 // Resumes or blocks a request paused by the NetworkDelegate::OnBeforeRequest
724 // handler. If |blocked| is true, the request is blocked and an error page is
725 // returned indicating so. This should only be called after Start is called
726 // and OnBeforeRequest returns true (signalling that the request should be
727 // paused).
728 void BeforeRequestComplete(int error);
730 void StartJob(URLRequestJob* job);
732 // Restarting involves replacing the current job with a new one such as what
733 // happens when following a HTTP redirect.
734 void RestartWithJob(URLRequestJob* job);
735 void PrepareToRestart();
737 // Detaches the job from this request in preparation for this object going
738 // away or the job being replaced. The job will not call us back when it has
739 // been orphaned.
740 void OrphanJob();
742 // Cancels the request and set the error and ssl info for this request to the
743 // passed values.
744 void DoCancel(int error, const SSLInfo& ssl_info);
746 // Called by the URLRequestJob when the headers are received, before any other
747 // method, to allow caching of load timing information.
748 void OnHeadersComplete();
750 // Notifies the network delegate that the request has been completed.
751 // This does not imply a successful completion. Also a canceled request is
752 // considered completed.
753 void NotifyRequestCompleted();
755 // Called by URLRequestJob to allow interception when the final response
756 // occurs.
757 void NotifyResponseStarted();
759 // These functions delegate to |delegate_| and may only be used if
760 // |delegate_| is not NULL. See URLRequest::Delegate for the meaning
761 // of these functions.
762 void NotifyAuthRequired(AuthChallengeInfo* auth_info);
763 void NotifyAuthRequiredComplete(NetworkDelegate::AuthRequiredResponse result);
764 void NotifyCertificateRequested(SSLCertRequestInfo* cert_request_info);
765 void NotifySSLCertificateError(const SSLInfo& ssl_info, bool fatal);
766 void NotifyReadCompleted(int bytes_read);
768 // These functions delegate to |network_delegate_| if it is not NULL.
769 // If |network_delegate_| is NULL, cookies can be used unless
770 // SetDefaultCookiePolicyToBlock() has been called.
771 bool CanGetCookies(const CookieList& cookie_list) const;
772 bool CanSetCookie(const std::string& cookie_line,
773 CookieOptions* options) const;
774 bool CanEnablePrivacyMode() const;
776 // Called just before calling a delegate that may block a request.
777 void OnCallToDelegate();
778 // Called when the delegate lets a request continue. Also called on
779 // cancellation.
780 void OnCallToDelegateComplete();
782 // Contextual information used for this request. Cannot be NULL. This contains
783 // most of the dependencies which are shared between requests (disk cache,
784 // cookie store, socket pool, etc.)
785 const URLRequestContext* context_;
787 NetworkDelegate* network_delegate_;
789 // Tracks the time spent in various load states throughout this request.
790 BoundNetLog net_log_;
792 scoped_refptr<URLRequestJob> job_;
793 scoped_ptr<UploadDataStream> upload_data_stream_;
794 std::vector<GURL> url_chain_;
795 GURL first_party_for_cookies_;
796 GURL delegate_redirect_url_;
797 std::string method_; // "GET", "POST", etc. Should be all uppercase.
798 std::string referrer_;
799 ReferrerPolicy referrer_policy_;
800 FirstPartyURLPolicy first_party_url_policy_;
801 HttpRequestHeaders extra_request_headers_;
802 int load_flags_; // Flags indicating the request type for the load;
803 // expected values are LOAD_* enums above.
805 // Never access methods of the |delegate_| directly. Always use the
806 // Notify... methods for this.
807 Delegate* delegate_;
809 // Current error status of the job. When no error has been encountered, this
810 // will be SUCCESS. If multiple errors have been encountered, this will be
811 // the first non-SUCCESS status seen.
812 URLRequestStatus status_;
814 // The HTTP response info, lazily initialized.
815 HttpResponseInfo response_info_;
817 // Tells us whether the job is outstanding. This is true from the time
818 // Start() is called to the time we dispatch RequestComplete and indicates
819 // whether the job is active.
820 bool is_pending_;
822 // Indicates if the request is in the process of redirecting to a new
823 // location. It is true from the time the headers complete until a
824 // new request begins.
825 bool is_redirecting_;
827 // Number of times we're willing to redirect. Used to guard against
828 // infinite redirects.
829 int redirect_limit_;
831 // Cached value for use after we've orphaned the job handling the
832 // first transaction in a request involving redirects.
833 UploadProgress final_upload_progress_;
835 // The priority level for this request. Objects like
836 // ClientSocketPool use this to determine which URLRequest to
837 // allocate sockets to first.
838 RequestPriority priority_;
840 // TODO(battre): The only consumer of the identifier_ is currently the
841 // web request API. We need to match identifiers of requests between the
842 // web request API and the web navigation API. As the URLRequest does not
843 // exist when the web navigation API is triggered, the tracking probably
844 // needs to be done outside of the URLRequest anyway. Therefore, this
845 // identifier should be deleted here. http://crbug.com/89321
846 // A globally unique identifier for this request.
847 const uint64 identifier_;
849 // True if this request is currently calling a delegate, or is blocked waiting
850 // for the URL request or network delegate to resume it.
851 bool calling_delegate_;
853 // An optional parameter that provides additional information about what
854 // |this| is currently being blocked by.
855 std::string blocked_by_;
856 bool use_blocked_by_as_load_param_;
858 base::debug::LeakTracker<URLRequest> leak_tracker_;
860 // Callback passed to the network delegate to notify us when a blocked request
861 // is ready to be resumed or canceled.
862 CompletionCallback before_request_callback_;
864 // Safe-guard to ensure that we do not send multiple "I am completed"
865 // messages to network delegate.
866 // TODO(battre): Remove this. http://crbug.com/89049
867 bool has_notified_completion_;
869 // Authentication data used by the NetworkDelegate for this request,
870 // if one is present. |auth_credentials_| may be filled in when calling
871 // |NotifyAuthRequired| on the NetworkDelegate. |auth_info_| holds
872 // the authentication challenge being handled by |NotifyAuthRequired|.
873 AuthCredentials auth_credentials_;
874 scoped_refptr<AuthChallengeInfo> auth_info_;
876 int64 received_response_content_length_;
878 base::TimeTicks creation_time_;
880 // Timing information for the most recent request. Its start times are
881 // populated during Start(), and the rest are populated in OnResponseReceived.
882 LoadTimingInfo load_timing_info_;
884 scoped_ptr<const base::debug::StackTrace> stack_trace_;
886 // Keeps track of whether or not OnBeforeNetworkStart has been called yet.
887 bool notified_before_network_start_;
889 // The cookie store to be used for this request.
890 scoped_refptr<CookieStore> cookie_store_;
892 // The proxy server used for this request, if any.
893 HostPortPair proxy_server_;
895 DISALLOW_COPY_AND_ASSIGN(URLRequest);
898 } // namespace net
900 #endif // NET_URL_REQUEST_URL_REQUEST_H_