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