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