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