Home | History | Annotate | Download | only in url_request
      1 // Copyright (c) 2011 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 #pragma once
      8 
      9 #include <map>
     10 #include <string>
     11 #include <vector>
     12 
     13 #include "base/debug/leak_tracker.h"
     14 #include "base/logging.h"
     15 #include "base/memory/linked_ptr.h"
     16 #include "base/memory/ref_counted.h"
     17 #include "base/string16.h"
     18 #include "base/threading/non_thread_safe.h"
     19 #include "googleurl/src/gurl.h"
     20 #include "net/base/completion_callback.h"
     21 #include "net/base/load_states.h"
     22 #include "net/base/net_log.h"
     23 #include "net/base/request_priority.h"
     24 #include "net/http/http_request_headers.h"
     25 #include "net/http/http_response_info.h"
     26 #include "net/url_request/url_request_status.h"
     27 
     28 namespace base {
     29 class Time;
     30 }  // namespace base
     31 
     32 class FilePath;
     33 
     34 // This stores the values of the Set-Cookie headers received during the request.
     35 // Each item in the vector corresponds to a Set-Cookie: line received,
     36 // excluding the "Set-Cookie:" part.
     37 typedef std::vector<std::string> ResponseCookies;
     38 
     39 namespace net {
     40 
     41 class CookieOptions;
     42 class HostPortPair;
     43 class IOBuffer;
     44 class SSLCertRequestInfo;
     45 class UploadData;
     46 class URLRequestContext;
     47 class URLRequestJob;
     48 class X509Certificate;
     49 
     50 //-----------------------------------------------------------------------------
     51 // A class  representing the asynchronous load of a data stream from an URL.
     52 //
     53 // The lifetime of an instance of this class is completely controlled by the
     54 // consumer, and the instance is not required to live on the heap or be
     55 // allocated in any special way.  It is also valid to delete an URLRequest
     56 // object during the handling of a callback to its delegate.  Of course, once
     57 // the URLRequest is deleted, no further callbacks to its delegate will occur.
     58 //
     59 // NOTE: All usage of all instances of this class should be on the same thread.
     60 //
     61 class URLRequest : public base::NonThreadSafe {
     62  public:
     63   // Callback function implemented by protocol handlers to create new jobs.
     64   // The factory may return NULL to indicate an error, which will cause other
     65   // factories to be queried.  If no factory handles the request, then the
     66   // default job will be used.
     67   typedef URLRequestJob* (ProtocolFactory)(URLRequest* request,
     68                                            const std::string& scheme);
     69 
     70   // HTTP request/response header IDs (via some preprocessor fun) for use with
     71   // SetRequestHeaderById and GetResponseHeaderById.
     72   enum {
     73 #define HTTP_ATOM(x) HTTP_ ## x,
     74 #include "net/http/http_atom_list.h"
     75 #undef HTTP_ATOM
     76   };
     77 
     78   // Derive from this class and add your own data members to associate extra
     79   // information with a URLRequest. Use GetUserData(key) and SetUserData()
     80   class UserData {
     81    public:
     82     UserData() {}
     83     virtual ~UserData() {}
     84   };
     85 
     86   // This class handles network interception.  Use with
     87   // (Un)RegisterRequestInterceptor.
     88   class Interceptor {
     89   public:
     90     virtual ~Interceptor() {}
     91 
     92     // Called for every request made.  Should return a new job to handle the
     93     // request if it should be intercepted, or NULL to allow the request to
     94     // be handled in the normal manner.
     95     virtual URLRequestJob* MaybeIntercept(URLRequest* request) = 0;
     96 
     97     // Called after having received a redirect response, but prior to the
     98     // the request delegate being informed of the redirect. Can return a new
     99     // job to replace the existing job if it should be intercepted, or NULL
    100     // to allow the normal handling to continue. If a new job is provided,
    101     // the delegate never sees the original redirect response, instead the
    102     // response produced by the intercept job will be returned.
    103     virtual URLRequestJob* MaybeInterceptRedirect(URLRequest* request,
    104                                                   const GURL& location);
    105 
    106     // Called after having received a final response, but prior to the
    107     // the request delegate being informed of the response. This is also
    108     // called when there is no server response at all to allow interception
    109     // on dns or network errors. Can return a new job to replace the existing
    110     // job if it should be intercepted, or NULL to allow the normal handling to
    111     // continue. If a new job is provided, the delegate never sees the original
    112     // response, instead the response produced by the intercept job will be
    113     // returned.
    114     virtual URLRequestJob* MaybeInterceptResponse(URLRequest* request);
    115   };
    116 
    117   // The delegate's methods are called from the message loop of the thread
    118   // on which the request's Start() method is called. See above for the
    119   // ordering of callbacks.
    120   //
    121   // The callbacks will be called in the following order:
    122   //   Start()
    123   //    - OnCertificateRequested* (zero or more calls, if the SSL server and/or
    124   //      SSL proxy requests a client certificate for authentication)
    125   //    - OnSSLCertificateError* (zero or one call, if the SSL server's
    126   //      certificate has an error)
    127   //    - OnReceivedRedirect* (zero or more calls, for the number of redirects)
    128   //    - OnAuthRequired* (zero or more calls, for the number of
    129   //      authentication failures)
    130   //    - OnResponseStarted
    131   //   Read() initiated by delegate
    132   //    - OnReadCompleted* (zero or more calls until all data is read)
    133   //
    134   // Read() must be called at least once. Read() returns true when it completed
    135   // immediately, and false if an IO is pending or if there is an error.  When
    136   // Read() returns false, the caller can check the Request's status() to see
    137   // if an error occurred, or if the IO is just pending.  When Read() returns
    138   // true with zero bytes read, it indicates the end of the response.
    139   //
    140   class Delegate {
    141    public:
    142     virtual ~Delegate() {}
    143 
    144     // Called upon a server-initiated redirect.  The delegate may call the
    145     // request's Cancel method to prevent the redirect from being followed.
    146     // Since there may be multiple chained redirects, there may also be more
    147     // than one redirect call.
    148     //
    149     // When this function is called, the request will still contain the
    150     // original URL, the destination of the redirect is provided in 'new_url'.
    151     // If the delegate does not cancel the request and |*defer_redirect| is
    152     // false, then the redirect will be followed, and the request's URL will be
    153     // changed to the new URL.  Otherwise if the delegate does not cancel the
    154     // request and |*defer_redirect| is true, then the redirect will be
    155     // followed once FollowDeferredRedirect is called on the URLRequest.
    156     //
    157     // The caller must set |*defer_redirect| to false, so that delegates do not
    158     // need to set it if they are happy with the default behavior of not
    159     // deferring redirect.
    160     virtual void OnReceivedRedirect(URLRequest* request,
    161                                     const GURL& new_url,
    162                                     bool* defer_redirect);
    163 
    164     // Called when we receive an authentication failure.  The delegate should
    165     // call request->SetAuth() with the user's credentials once it obtains them,
    166     // or request->CancelAuth() to cancel the login and display the error page.
    167     // When it does so, the request will be reissued, restarting the sequence
    168     // of On* callbacks.
    169     virtual void OnAuthRequired(URLRequest* request,
    170                                 AuthChallengeInfo* auth_info);
    171 
    172     // Called when we receive an SSL CertificateRequest message for client
    173     // authentication.  The delegate should call
    174     // request->ContinueWithCertificate() with the client certificate the user
    175     // selected, or request->ContinueWithCertificate(NULL) to continue the SSL
    176     // handshake without a client certificate.
    177     virtual void OnCertificateRequested(
    178         URLRequest* request,
    179         SSLCertRequestInfo* cert_request_info);
    180 
    181     // Called when using SSL and the server responds with a certificate with
    182     // an error, for example, whose common name does not match the common name
    183     // we were expecting for that host.  The delegate should either do the
    184     // safe thing and Cancel() the request or decide to proceed by calling
    185     // ContinueDespiteLastError().  cert_error is a ERR_* error code
    186     // indicating what's wrong with the certificate.
    187     virtual void OnSSLCertificateError(URLRequest* request,
    188                                        int cert_error,
    189                                        X509Certificate* cert);
    190 
    191     // Called when reading cookies. |blocked_by_policy| is true if access to
    192     // cookies was denied due to content settings. This method will never be
    193     // invoked when LOAD_DO_NOT_SEND_COOKIES is specified.
    194     virtual void OnGetCookies(URLRequest* request, bool blocked_by_policy);
    195 
    196     // Called when a cookie is set. |blocked_by_policy| is true if the cookie
    197     // was rejected due to content settings. This method will never be invoked
    198     // when LOAD_DO_NOT_SAVE_COOKIES is specified.
    199     virtual void OnSetCookie(URLRequest* request,
    200                              const std::string& cookie_line,
    201                              const CookieOptions& options,
    202                              bool blocked_by_policy);
    203 
    204     // After calling Start(), the delegate will receive an OnResponseStarted
    205     // callback when the request has completed.  If an error occurred, the
    206     // request->status() will be set.  On success, all redirects have been
    207     // followed and the final response is beginning to arrive.  At this point,
    208     // meta data about the response is available, including for example HTTP
    209     // response headers if this is a request for a HTTP resource.
    210     virtual void OnResponseStarted(URLRequest* request) = 0;
    211 
    212     // Called when the a Read of the response body is completed after an
    213     // IO_PENDING status from a Read() call.
    214     // The data read is filled into the buffer which the caller passed
    215     // to Read() previously.
    216     //
    217     // If an error occurred, request->status() will contain the error,
    218     // and bytes read will be -1.
    219     virtual void OnReadCompleted(URLRequest* request, int bytes_read) = 0;
    220   };
    221 
    222   // Initialize an URL request.
    223   URLRequest(const GURL& url, Delegate* delegate);
    224 
    225   // If destroyed after Start() has been called but while IO is pending,
    226   // then the request will be effectively canceled and the delegate
    227   // will not have any more of its methods called.
    228   ~URLRequest();
    229 
    230   // The user data allows the clients to associate data with this request.
    231   // Multiple user data values can be stored under different keys.
    232   // This request will TAKE OWNERSHIP of the given data pointer, and will
    233   // delete the object if it is changed or the request is destroyed.
    234   UserData* GetUserData(const void* key) const;
    235   void SetUserData(const void* key, UserData* data);
    236 
    237   // Registers a new protocol handler for the given scheme. If the scheme is
    238   // already handled, this will overwrite the given factory. To delete the
    239   // protocol factory, use NULL for the factory BUT this WILL NOT put back
    240   // any previously registered protocol factory. It will have returned
    241   // the previously registered factory (or NULL if none is registered) when
    242   // the scheme was first registered so that the caller can manually put it
    243   // back if desired.
    244   //
    245   // The scheme must be all-lowercase ASCII. See the ProtocolFactory
    246   // declaration for its requirements.
    247   //
    248   // The registered protocol factory may return NULL, which will cause the
    249   // regular "built-in" protocol factory to be used.
    250   //
    251   static ProtocolFactory* RegisterProtocolFactory(const std::string& scheme,
    252                                                   ProtocolFactory* factory);
    253 
    254   // Registers or unregisters a network interception class.
    255   static void RegisterRequestInterceptor(Interceptor* interceptor);
    256   static void UnregisterRequestInterceptor(Interceptor* interceptor);
    257 
    258   // Returns true if the scheme can be handled by URLRequest. False otherwise.
    259   static bool IsHandledProtocol(const std::string& scheme);
    260 
    261   // Returns true if the url can be handled by URLRequest. False otherwise.
    262   // The function returns true for invalid urls because URLRequest knows how
    263   // to handle those.
    264   // NOTE: This will also return true for URLs that are handled by
    265   // ProtocolFactories that only work for requests that are scoped to a
    266   // Profile.
    267   static bool IsHandledURL(const GURL& url);
    268 
    269   // Allow access to file:// on ChromeOS for tests.
    270   static void AllowFileAccess();
    271   static bool IsFileAccessAllowed();
    272 
    273   // The original url is the url used to initialize the request, and it may
    274   // differ from the url if the request was redirected.
    275   const GURL& original_url() const { return url_chain_.front(); }
    276   // The chain of urls traversed by this request.  If the request had no
    277   // redirects, this vector will contain one element.
    278   const std::vector<GURL>& url_chain() const { return url_chain_; }
    279   const GURL& url() const { return url_chain_.back(); }
    280 
    281   // The URL that should be consulted for the third-party cookie blocking
    282   // policy.
    283   const GURL& first_party_for_cookies() const {
    284       return first_party_for_cookies_;
    285   }
    286   // This method may be called before Start() or FollowDeferredRedirect() is
    287   // called.
    288   void set_first_party_for_cookies(const GURL& first_party_for_cookies);
    289 
    290   // The request method, as an uppercase string.  "GET" is the default value.
    291   // The request method may only be changed before Start() is called and
    292   // should only be assigned an uppercase value.
    293   const std::string& method() const { return method_; }
    294   void set_method(const std::string& method);
    295 
    296   // The referrer URL for the request.  This header may actually be suppressed
    297   // from the underlying network request for security reasons (e.g., a HTTPS
    298   // URL will not be sent as the referrer for a HTTP request).  The referrer
    299   // may only be changed before Start() is called.
    300   const std::string& referrer() const { return referrer_; }
    301   void set_referrer(const std::string& referrer);
    302   // Returns the referrer header with potential username and password removed.
    303   GURL GetSanitizedReferrer() const;
    304 
    305   // The delegate of the request.  This value may be changed at any time,
    306   // and it is permissible for it to be null.
    307   Delegate* delegate() const { return delegate_; }
    308   void set_delegate(Delegate* delegate) { delegate_ = delegate; }
    309 
    310   // The data comprising the request message body is specified as a sequence of
    311   // data segments and/or files containing data to upload.  These methods may
    312   // be called to construct the data sequence to upload, and they may only be
    313   // called before Start() is called.  For POST requests, the user must call
    314   // SetRequestHeaderBy{Id,Name} to set the Content-Type of the request to the
    315   // appropriate value before calling Start().
    316   //
    317   // When uploading data, bytes_len must be non-zero.
    318   // When uploading a file range, length must be non-zero. If length
    319   // exceeds the end-of-file, the upload is clipped at end-of-file. If the
    320   // expected modification time is provided (non-zero), it will be used to
    321   // check if the underlying file has been changed or not. The granularity of
    322   // the time comparison is 1 second since time_t precision is used in WebKit.
    323   void AppendBytesToUpload(const char* bytes, int bytes_len);  // takes a copy
    324   void AppendFileRangeToUpload(const FilePath& file_path,
    325                                uint64 offset, uint64 length,
    326                                const base::Time& expected_modification_time);
    327   void AppendFileToUpload(const FilePath& file_path) {
    328     AppendFileRangeToUpload(file_path, 0, kuint64max, base::Time());
    329   }
    330 
    331   // Indicates that the request body should be sent using chunked transfer
    332   // encoding. This method may only be called before Start() is called.
    333   void EnableChunkedUpload();
    334 
    335   // Appends the given bytes to the request's upload data to be sent
    336   // immediately via chunked transfer encoding. When all data has been sent,
    337   // call MarkEndOfChunks() to indicate the end of upload data.
    338   //
    339   // This method may be called only after calling EnableChunkedUpload().
    340   void AppendChunkToUpload(const char* bytes,
    341                            int bytes_len,
    342                            bool is_last_chunk);
    343 
    344   // Set the upload data directly.
    345   void set_upload(UploadData* upload);
    346 
    347   // Get the upload data directly.
    348   UploadData* get_upload();
    349 
    350   // Returns true if the request has a non-empty message body to upload.
    351   bool has_upload() const;
    352 
    353   // Set an extra request header by ID or name.  These methods may only be
    354   // called before Start() is called.  It is an error to call it later.
    355   void SetExtraRequestHeaderById(int header_id, const std::string& value,
    356                                  bool overwrite);
    357   void SetExtraRequestHeaderByName(const std::string& name,
    358                                    const std::string& value, bool overwrite);
    359 
    360   // Sets all extra request headers.  Any extra request headers set by other
    361   // methods are overwritten by this method.  This method may only be called
    362   // before Start() is called.  It is an error to call it later.
    363   void SetExtraRequestHeaders(const HttpRequestHeaders& headers);
    364 
    365   const HttpRequestHeaders& extra_request_headers() const {
    366     return extra_request_headers_;
    367   }
    368 
    369   // Returns the current load state for the request.
    370   LoadState GetLoadState() const;
    371 
    372   // Returns the current upload progress in bytes.
    373   uint64 GetUploadProgress() const;
    374 
    375   // Get response header(s) by ID or name.  These methods may only be called
    376   // once the delegate's OnResponseStarted method has been called.  Headers
    377   // that appear more than once in the response are coalesced, with values
    378   // separated by commas (per RFC 2616). This will not work with cookies since
    379   // comma can be used in cookie values.
    380   // TODO(darin): add API to enumerate response headers.
    381   void GetResponseHeaderById(int header_id, std::string* value);
    382   void GetResponseHeaderByName(const std::string& name, std::string* value);
    383 
    384   // Get all response headers, \n-delimited and \n\0-terminated.  This includes
    385   // the response status line.  Restrictions on GetResponseHeaders apply.
    386   void GetAllResponseHeaders(std::string* headers);
    387 
    388   // The time at which the returned response was requested.  For cached
    389   // responses, this is the last time the cache entry was validated.
    390   const base::Time& request_time() const {
    391     return response_info_.request_time;
    392   }
    393 
    394   // The time at which the returned response was generated.  For cached
    395   // responses, this is the last time the cache entry was validated.
    396   const base::Time& response_time() const {
    397     return response_info_.response_time;
    398   }
    399 
    400   // Indicate if this response was fetched from disk cache.
    401   bool was_cached() const { return response_info_.was_cached; }
    402 
    403   // True if response could use alternate protocol. However, browser will
    404   // ignore the alternate protocol if spdy is not enabled.
    405   bool was_fetched_via_spdy() const {
    406     return response_info_.was_fetched_via_spdy;
    407   }
    408 
    409   // Returns true if the URLRequest was delivered after NPN is negotiated,
    410   // using either SPDY or HTTP.
    411   bool was_npn_negotiated() const {
    412     return response_info_.was_npn_negotiated;
    413   }
    414 
    415   // Returns true if the URLRequest was delivered through a proxy.
    416   bool was_fetched_via_proxy() const {
    417     return response_info_.was_fetched_via_proxy;
    418   }
    419 
    420   // Returns the host and port that the content was fetched from.  See
    421   // http_response_info.h for caveats relating to cached content.
    422   HostPortPair GetSocketAddress() const;
    423 
    424   // Get all response headers, as a HttpResponseHeaders object.  See comments
    425   // in HttpResponseHeaders class as to the format of the data.
    426   HttpResponseHeaders* response_headers() const;
    427 
    428   // Get the SSL connection info.
    429   const SSLInfo& ssl_info() const {
    430     return response_info_.ssl_info;
    431   }
    432 
    433   // Returns the cookie values included in the response, if the request is one
    434   // that can have cookies.  Returns true if the request is a cookie-bearing
    435   // type, false otherwise.  This method may only be called once the
    436   // delegate's OnResponseStarted method has been called.
    437   bool GetResponseCookies(ResponseCookies* cookies);
    438 
    439   // Get the mime type.  This method may only be called once the delegate's
    440   // OnResponseStarted method has been called.
    441   void GetMimeType(std::string* mime_type);
    442 
    443   // Get the charset (character encoding).  This method may only be called once
    444   // the delegate's OnResponseStarted method has been called.
    445   void GetCharset(std::string* charset);
    446 
    447   // Returns the HTTP response code (e.g., 200, 404, and so on).  This method
    448   // may only be called once the delegate's OnResponseStarted method has been
    449   // called.  For non-HTTP requests, this method returns -1.
    450   int GetResponseCode();
    451 
    452   // Get the HTTP response info in its entirety.
    453   const HttpResponseInfo& response_info() const { return response_info_; }
    454 
    455   // Access the LOAD_* flags modifying this request (see load_flags.h).
    456   int load_flags() const { return load_flags_; }
    457   void set_load_flags(int flags) { load_flags_ = flags; }
    458 
    459   // Returns true if the request is "pending" (i.e., if Start() has been called,
    460   // and the response has not yet been called).
    461   bool is_pending() const { return is_pending_; }
    462 
    463   // Returns the error status of the request.
    464   const URLRequestStatus& status() const { return status_; }
    465 
    466   // Returns a globally unique identifier for this request.
    467   uint64 identifier() const { return identifier_; }
    468 
    469   // This method is called to start the request.  The delegate will receive
    470   // a OnResponseStarted callback when the request is started.
    471   void Start();
    472 
    473   // This method may be called at any time after Start() has been called to
    474   // cancel the request.  This method may be called many times, and it has
    475   // no effect once the response has completed.  It is guaranteed that no
    476   // methods of the delegate will be called after the request has been
    477   // cancelled, except that this may call the delegate's OnReadCompleted()
    478   // during the call to Cancel itself.
    479   void Cancel();
    480 
    481   // Cancels the request and sets the error to |os_error| (see net_error_list.h
    482   // for values).
    483   void SimulateError(int os_error);
    484 
    485   // Cancels the request and sets the error to |os_error| (see net_error_list.h
    486   // for values) and attaches |ssl_info| as the SSLInfo for that request.  This
    487   // is useful to attach a certificate and certificate error to a canceled
    488   // request.
    489   void SimulateSSLError(int os_error, const SSLInfo& ssl_info);
    490 
    491   // Read initiates an asynchronous read from the response, and must only
    492   // be called after the OnResponseStarted callback is received with a
    493   // successful status.
    494   // If data is available, Read will return true, and the data and length will
    495   // be returned immediately.  If data is not available, Read returns false,
    496   // and an asynchronous Read is initiated.  The Read is finished when
    497   // the caller receives the OnReadComplete callback.  Unless the request was
    498   // cancelled, OnReadComplete will always be called, even if the read failed.
    499   //
    500   // The buf parameter is a buffer to receive the data.  If the operation
    501   // completes asynchronously, the implementation will reference the buffer
    502   // until OnReadComplete is called.  The buffer must be at least max_bytes in
    503   // length.
    504   //
    505   // The max_bytes parameter is the maximum number of bytes to read.
    506   //
    507   // The bytes_read parameter is an output parameter containing the
    508   // the number of bytes read.  A value of 0 indicates that there is no
    509   // more data available to read from the stream.
    510   //
    511   // If a read error occurs, Read returns false and the request->status
    512   // will be set to an error.
    513   bool Read(IOBuffer* buf, int max_bytes, int* bytes_read);
    514 
    515   // If this request is being cached by the HTTP cache, stop subsequent caching.
    516   // Note that this method has no effect on other (simultaneous or not) requests
    517   // for the same resource. The typical example is a request that results in
    518   // the data being stored to disk (downloaded instead of rendered) so we don't
    519   // want to store it twice.
    520   void StopCaching();
    521 
    522   // This method may be called to follow a redirect that was deferred in
    523   // response to an OnReceivedRedirect call.
    524   void FollowDeferredRedirect();
    525 
    526   // One of the following two methods should be called in response to an
    527   // OnAuthRequired() callback (and only then).
    528   // SetAuth will reissue the request with the given credentials.
    529   // CancelAuth will give up and display the error page.
    530   void SetAuth(const string16& username, const string16& password);
    531   void CancelAuth();
    532 
    533   // This method can be called after the user selects a client certificate to
    534   // instruct this URLRequest to continue with the request with the
    535   // certificate.  Pass NULL if the user doesn't have a client certificate.
    536   void ContinueWithCertificate(X509Certificate* client_cert);
    537 
    538   // This method can be called after some error notifications to instruct this
    539   // URLRequest to ignore the current error and continue with the request.  To
    540   // cancel the request instead, call Cancel().
    541   void ContinueDespiteLastError();
    542 
    543   // Used to specify the context (cookie store, cache) for this request.
    544   URLRequestContext* context() const;
    545   void set_context(URLRequestContext* context);
    546 
    547   const BoundNetLog& net_log() const { return net_log_; }
    548 
    549   // Returns the expected content size if available
    550   int64 GetExpectedContentSize() const;
    551 
    552   // Returns the priority level for this request.
    553   RequestPriority priority() const { return priority_; }
    554   void set_priority(RequestPriority priority) {
    555 #ifdef ANDROID
    556     DCHECK_GE(static_cast<int>(priority), static_cast<int>(HIGHEST));
    557     DCHECK_LT(static_cast<int>(priority), static_cast<int>(NUM_PRIORITIES));
    558 #else
    559     DCHECK_GE(priority, HIGHEST);
    560     DCHECK_LT(priority, NUM_PRIORITIES);
    561 #endif
    562     priority_ = priority;
    563   }
    564 
    565 #ifdef UNIT_TEST
    566   URLRequestJob* job() { return job_; }
    567 #endif
    568 
    569  protected:
    570   // Allow the URLRequestJob class to control the is_pending() flag.
    571   void set_is_pending(bool value) { is_pending_ = value; }
    572 
    573   // Allow the URLRequestJob class to set our status too
    574   void set_status(const URLRequestStatus& value) { status_ = value; }
    575 
    576   // Allow the URLRequestJob to redirect this request.  Returns OK if
    577   // successful, otherwise an error code is returned.
    578   int Redirect(const GURL& location, int http_status_code);
    579 
    580   // Called by URLRequestJob to allow interception when a redirect occurs.
    581   void ReceivedRedirect(const GURL& location, bool* defer_redirect);
    582 
    583   // Called by URLRequestJob to allow interception when the final response
    584   // occurs.
    585   void ResponseStarted();
    586 
    587   // Allow an interceptor's URLRequestJob to restart this request.
    588   // Should only be called if the original job has not started a response.
    589   void Restart();
    590 
    591  private:
    592   friend class URLRequestJob;
    593   typedef std::map<const void*, linked_ptr<UserData> > UserDataMap;
    594 
    595   void StartInternal();
    596 
    597   // Resumes or blocks a request paused by the NetworkDelegate::OnBeforeRequest
    598   // handler. If |blocked| is true, the request is blocked and an error page is
    599   // returned indicating so. This should only be called after Start is called
    600   // and OnBeforeRequest returns true (signalling that the request should be
    601   // paused).
    602   void BeforeRequestComplete(int error);
    603 
    604   void StartJob(URLRequestJob* job);
    605 
    606   // Restarting involves replacing the current job with a new one such as what
    607   // happens when following a HTTP redirect.
    608   void RestartWithJob(URLRequestJob* job);
    609   void PrepareToRestart();
    610 
    611   // Detaches the job from this request in preparation for this object going
    612   // away or the job being replaced. The job will not call us back when it has
    613   // been orphaned.
    614   void OrphanJob();
    615 
    616   // Cancels the request and set the error and ssl info for this request to the
    617   // passed values.
    618   void DoCancel(int os_error, const SSLInfo& ssl_info);
    619 
    620   // Contextual information used for this request (can be NULL). This contains
    621   // most of the dependencies which are shared between requests (disk cache,
    622   // cookie store, socket pool, etc.)
    623   scoped_refptr<URLRequestContext> context_;
    624 
    625   // Tracks the time spent in various load states throughout this request.
    626   BoundNetLog net_log_;
    627 
    628   scoped_refptr<URLRequestJob> job_;
    629   scoped_refptr<UploadData> upload_;
    630   std::vector<GURL> url_chain_;
    631   GURL first_party_for_cookies_;
    632   GURL delegate_redirect_url_;
    633   std::string method_;  // "GET", "POST", etc. Should be all uppercase.
    634   std::string referrer_;
    635   HttpRequestHeaders extra_request_headers_;
    636   int load_flags_;  // Flags indicating the request type for the load;
    637                     // expected values are LOAD_* enums above.
    638 
    639   Delegate* delegate_;
    640 
    641   // Current error status of the job. When no error has been encountered, this
    642   // will be SUCCESS. If multiple errors have been encountered, this will be
    643   // the first non-SUCCESS status seen.
    644   URLRequestStatus status_;
    645 
    646   // The HTTP response info, lazily initialized.
    647   HttpResponseInfo response_info_;
    648 
    649   // Tells us whether the job is outstanding. This is true from the time
    650   // Start() is called to the time we dispatch RequestComplete and indicates
    651   // whether the job is active.
    652   bool is_pending_;
    653 
    654   // Externally-defined data accessible by key
    655   UserDataMap user_data_;
    656 
    657   // Number of times we're willing to redirect.  Used to guard against
    658   // infinite redirects.
    659   int redirect_limit_;
    660 
    661   // Cached value for use after we've orphaned the job handling the
    662   // first transaction in a request involving redirects.
    663   uint64 final_upload_progress_;
    664 
    665   // The priority level for this request.  Objects like ClientSocketPool use
    666   // this to determine which URLRequest to allocate sockets to first.
    667   RequestPriority priority_;
    668 
    669   // A globally unique identifier for this request.
    670   const uint64 identifier_;
    671 
    672   base::debug::LeakTracker<URLRequest> leak_tracker_;
    673 
    674   // Callback passed to the network delegate to notify us when a blocked request
    675   // is ready to be resumed or canceled.
    676   CompletionCallbackImpl<URLRequest> before_request_callback_;
    677 
    678   DISALLOW_COPY_AND_ASSIGN(URLRequest);
    679 };
    680 
    681 }  // namespace net
    682 
    683 #endif  // NET_URL_REQUEST_URL_REQUEST_H_
    684