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.
5 #ifndef NET_URL_REQUEST_URL_FETCHER_CORE_H_
6 #define NET_URL_REQUEST_URL_FETCHER_CORE_H_
11 #include "base/basictypes.h"
12 #include "base/compiler_specific.h"
13 #include "base/debug/stack_trace.h"
14 #include "base/files/file_path.h"
15 #include "base/lazy_instance.h"
16 #include "base/memory/ref_counted.h"
17 #include "base/memory/scoped_ptr.h"
18 #include "base/timer/timer.h"
19 #include "net/base/host_port_pair.h"
20 #include "net/http/http_request_headers.h"
21 #include "net/url_request/url_fetcher.h"
22 #include "net/url_request/url_request.h"
23 #include "net/url_request/url_request_status.h"
27 class SingleThreadTaskRunner
;
31 class DrainableIOBuffer
;
32 class HttpResponseHeaders
;
34 class URLFetcherDelegate
;
35 class URLFetcherResponseWriter
;
36 class URLRequestContextGetter
;
37 class URLRequestThrottlerEntryInterface
;
40 : public base::RefCountedThreadSafe
<URLFetcherCore
>,
41 public URLRequest::Delegate
{
43 URLFetcherCore(URLFetcher
* fetcher
,
44 const GURL
& original_url
,
45 URLFetcher::RequestType request_type
,
46 URLFetcherDelegate
* d
);
48 // Starts the load. It's important that this not happen in the constructor
49 // because it causes the IO thread to begin AddRef()ing and Release()ing
50 // us. If our caller hasn't had time to fully construct us and take a
51 // reference, the IO thread could interrupt things, run a task, Release()
52 // us, and destroy us, leaving the caller with an already-destroyed object
53 // when construction finishes.
56 // Stops any in-progress load and ensures no callback will happen. It is
57 // safe to call this multiple times.
60 // URLFetcher-like functions.
62 // For POST requests, set |content_type| to the MIME type of the
63 // content and set |content| to the data to upload.
64 void SetUploadData(const std::string
& upload_content_type
,
65 const std::string
& upload_content
);
66 void SetUploadFilePath(const std::string
& upload_content_type
,
67 const base::FilePath
& file_path
,
70 scoped_refptr
<base::TaskRunner
> file_task_runner
);
71 void SetChunkedUpload(const std::string
& upload_content_type
);
72 // Adds a block of data to be uploaded in a POST body. This can only be
73 // called after Start().
74 void AppendChunkToUpload(const std::string
& data
, bool is_last_chunk
);
75 // |flags| are flags to apply to the load operation--these should be
76 // one or more of the LOAD_* flags defined in net/base/load_flags.h.
77 void SetLoadFlags(int load_flags
);
78 int GetLoadFlags() const;
79 void SetReferrer(const std::string
& referrer
);
80 void SetReferrerPolicy(URLRequest::ReferrerPolicy referrer_policy
);
81 void SetExtraRequestHeaders(const std::string
& extra_request_headers
);
82 void AddExtraRequestHeader(const std::string
& header_line
);
83 void SetRequestContext(URLRequestContextGetter
* request_context_getter
);
84 // Set the URL that should be consulted for the third-party cookie
86 void SetFirstPartyForCookies(const GURL
& first_party_for_cookies
);
87 // Set the key and data callback that is used when setting the user
88 // data on any URLRequest objects this object creates.
89 void SetURLRequestUserData(
91 const URLFetcher::CreateDataCallback
& create_data_callback
);
92 void SetStopOnRedirect(bool stop_on_redirect
);
93 void SetAutomaticallyRetryOn5xx(bool retry
);
94 void SetMaxRetriesOn5xx(int max_retries
);
95 int GetMaxRetriesOn5xx() const;
96 base::TimeDelta
GetBackoffDelay() const;
97 void SetAutomaticallyRetryOnNetworkChanges(int max_retries
);
98 void SaveResponseToFileAtPath(
99 const base::FilePath
& file_path
,
100 scoped_refptr
<base::SequencedTaskRunner
> file_task_runner
);
101 void SaveResponseToTemporaryFile(
102 scoped_refptr
<base::SequencedTaskRunner
> file_task_runner
);
103 void SaveResponseWithWriter(
104 scoped_ptr
<URLFetcherResponseWriter
> response_writer
);
105 HttpResponseHeaders
* GetResponseHeaders() const;
106 HostPortPair
GetSocketAddress() const;
107 bool WasFetchedViaProxy() const;
108 const GURL
& GetOriginalURL() const;
109 const GURL
& GetURL() const;
110 const URLRequestStatus
& GetStatus() const;
111 int GetResponseCode() const;
112 const ResponseCookies
& GetCookies() const;
113 // Reports that the received content was malformed (i.e. failed parsing
114 // or validation). This makes the throttling logic that does exponential
115 // back-off when servers are having problems treat the current request as
116 // a failure. Your call to this method will be ignored if your request is
117 // already considered a failure based on the HTTP response code or response
119 void ReceivedContentWasMalformed();
120 bool GetResponseAsString(std::string
* out_response_string
) const;
121 bool GetResponseAsFilePath(bool take_ownership
,
122 base::FilePath
* out_response_path
);
124 // Overridden from URLRequest::Delegate:
125 void OnReceivedRedirect(URLRequest
* request
,
126 const RedirectInfo
& redirect_info
,
127 bool* defer_redirect
) override
;
128 void OnResponseStarted(URLRequest
* request
) override
;
129 void OnReadCompleted(URLRequest
* request
, int bytes_read
) override
;
130 void OnCertificateRequested(URLRequest
* request
,
131 SSLCertRequestInfo
* cert_request_info
) override
;
133 URLFetcherDelegate
* delegate() const { return delegate_
; }
134 static void CancelAll();
135 static int GetNumFetcherCores();
136 static void SetEnableInterceptionForTests(bool enabled
);
137 static void SetIgnoreCertificateRequests(bool ignored
);
140 friend class base::RefCountedThreadSafe
<URLFetcherCore
>;
147 void AddURLFetcherCore(URLFetcherCore
* core
);
148 void RemoveURLFetcherCore(URLFetcherCore
* core
);
153 return fetchers_
.size();
157 std::set
<URLFetcherCore
*> fetchers_
;
159 DISALLOW_COPY_AND_ASSIGN(Registry
);
162 ~URLFetcherCore() override
;
164 // Wrapper functions that allow us to ensure actions happen on the right
166 void StartOnIOThread();
167 void StartURLRequest();
168 void DidInitializeWriter(int result
);
169 void StartURLRequestWhenAppropriate();
170 void CancelURLRequest(int error
);
171 void OnCompletedURLRequest(base::TimeDelta backoff_delay
);
172 void InformDelegateFetchIsComplete();
173 void NotifyMalformedContent();
174 void DidFinishWriting(int result
);
175 void RetryOrCompleteUrlFetch();
177 // Deletes the request, removes it from the registry, and removes the
178 // destruction observer.
179 void ReleaseRequest();
181 // Returns the max value of exponential back-off release time for
182 // |original_url_| and |url_|.
183 base::TimeTicks
GetBackoffReleaseTime();
185 void CompleteAddingUploadDataChunk(const std::string
& data
,
188 // Writes all bytes stored in |data| with |response_writer_|.
189 // Returns OK if all bytes in |data| get written synchronously. Otherwise,
190 // returns ERR_IO_PENDING or a network error code.
191 int WriteBuffer(scoped_refptr
<DrainableIOBuffer
> data
);
193 // Used to implement WriteBuffer().
194 void DidWriteBuffer(scoped_refptr
<DrainableIOBuffer
> data
, int result
);
196 // Read response bytes from the request.
199 // Notify Delegate about the progress of upload/download.
200 void InformDelegateUploadProgress();
201 void InformDelegateUploadProgressInDelegateThread(int64 current
, int64 total
);
202 void InformDelegateDownloadProgress();
203 void InformDelegateDownloadProgressInDelegateThread(int64 current
,
206 URLFetcher
* fetcher_
; // Corresponding fetcher object
207 GURL original_url_
; // The URL we were asked to fetch
208 GURL url_
; // The URL we eventually wound up at
209 URLFetcher::RequestType request_type_
; // What type of request is this?
210 URLRequestStatus status_
; // Status of the request
211 URLFetcherDelegate
* delegate_
; // Object to notify on completion
212 // Task runner for the creating thread. Used to interact with the delegate.
213 scoped_refptr
<base::SingleThreadTaskRunner
> delegate_task_runner_
;
214 // Task runner for network operations.
215 scoped_refptr
<base::SingleThreadTaskRunner
> network_task_runner_
;
216 // Task runner for upload file access.
217 scoped_refptr
<base::TaskRunner
> upload_file_task_runner_
;
218 scoped_ptr
<URLRequest
> request_
; // The actual request this wraps
219 int load_flags_
; // Flags for the load operation
220 int response_code_
; // HTTP status code for the request
221 scoped_refptr
<IOBuffer
> buffer_
;
223 scoped_refptr
<URLRequestContextGetter
> request_context_getter_
;
224 // Cookie/cache info for the request
225 GURL first_party_for_cookies_
; // The first party URL for the request
226 // The user data to add to each newly-created URLRequest.
227 const void* url_request_data_key_
;
228 URLFetcher::CreateDataCallback url_request_create_data_callback_
;
229 ResponseCookies cookies_
; // Response cookies
230 HttpRequestHeaders extra_request_headers_
;
231 scoped_refptr
<HttpResponseHeaders
> response_headers_
;
232 bool was_fetched_via_proxy_
;
233 HostPortPair socket_address_
;
235 bool upload_content_set_
; // SetUploadData has been called
236 std::string upload_content_
; // HTTP POST payload
237 base::FilePath upload_file_path_
; // Path to file containing POST payload
238 uint64 upload_range_offset_
; // Offset from the beginning of the file
240 uint64 upload_range_length_
; // The length of the part of file to be
242 std::string upload_content_type_
; // MIME type of POST payload
243 std::string referrer_
; // HTTP Referer header value and policy
244 URLRequest::ReferrerPolicy referrer_policy_
;
245 bool is_chunked_upload_
; // True if using chunked transfer encoding
247 // Used to determine how long to wait before making a request or doing a
250 // Both of them can only be accessed on the IO thread.
252 // To determine the proper backoff timing, throttler entries for
253 // both |original_URL| and |url| are needed. For example, consider
254 // the case that URL A redirects to URL B, for which the server
255 // returns a 500 response. In this case, the exponential back-off
256 // release time of URL A won't increase. If only the backoff
257 // constraints for URL A are considered, too many requests for URL A
258 // may be sent in a short period of time.
260 // Both of these will be NULL if
261 // URLRequestContext::throttler_manager() is NULL.
262 scoped_refptr
<URLRequestThrottlerEntryInterface
>
263 original_url_throttler_entry_
;
264 scoped_refptr
<URLRequestThrottlerEntryInterface
> url_throttler_entry_
;
266 // True if the URLFetcher has been cancelled.
269 // Writer object to write response to the destination like file and string.
270 scoped_ptr
<URLFetcherResponseWriter
> response_writer_
;
272 // By default any server-initiated redirects are automatically followed. If
273 // this flag is set to true, however, a redirect will halt the fetch and call
274 // back to to the delegate immediately.
275 bool stop_on_redirect_
;
276 // True when we're actually stopped due to a redirect halted by the above. We
277 // use this to ensure that |url_| is set to the redirect destination rather
278 // than the originally-fetched URL.
279 bool stopped_on_redirect_
;
281 // If |automatically_retry_on_5xx_| is false, 5xx responses will be
282 // propagated to the observer, if it is true URLFetcher will automatically
283 // re-execute the request, after the back-off delay has expired.
285 bool automatically_retry_on_5xx_
;
286 // |num_retries_on_5xx_| indicates how many times we've failed to successfully
287 // fetch this URL due to 5xx responses. Once this value exceeds the maximum
288 // number of retries specified by the owner URLFetcher instance,
290 int num_retries_on_5xx_
;
291 // Maximum retries allowed when 5xx responses are received.
292 int max_retries_on_5xx_
;
293 // Back-off time delay. 0 by default.
294 base::TimeDelta backoff_delay_
;
296 // The number of retries that have been attempted due to ERR_NETWORK_CHANGED.
297 int num_retries_on_network_changes_
;
298 // Maximum retries allowed when the request fails with ERR_NETWORK_CHANGED.
300 int max_retries_on_network_changes_
;
302 // Timer to poll the progress of uploading for POST and PUT requests.
303 // When crbug.com/119629 is fixed, scoped_ptr is not necessary here.
304 scoped_ptr
<base::RepeatingTimer
<URLFetcherCore
> >
305 upload_progress_checker_timer_
;
306 // Number of bytes sent so far.
307 int64 current_upload_bytes_
;
308 // Number of bytes received so far.
309 int64 current_response_bytes_
;
310 // Total expected bytes to receive (-1 if it cannot be determined).
311 int64 total_response_bytes_
;
313 // TODO(willchan): Get rid of this after debugging crbug.com/90971.
314 base::debug::StackTrace stack_trace_
;
316 static base::LazyInstance
<Registry
> g_registry
;
318 DISALLOW_COPY_AND_ASSIGN(URLFetcherCore
);
323 #endif // NET_URL_REQUEST_URL_FETCHER_CORE_H_