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