OLD | NEW |
| (Empty) |
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_JOB_H_ | |
6 #define NET_URL_REQUEST_URL_REQUEST_JOB_H_ | |
7 | |
8 #include <string> | |
9 #include <vector> | |
10 | |
11 #include "base/memory/ref_counted.h" | |
12 #include "base/memory/scoped_ptr.h" | |
13 #include "base/memory/weak_ptr.h" | |
14 #include "base/message_loop/message_loop.h" | |
15 #include "base/power_monitor/power_observer.h" | |
16 #include "net/base/host_port_pair.h" | |
17 #include "net/base/load_states.h" | |
18 #include "net/base/net_export.h" | |
19 #include "net/base/request_priority.h" | |
20 #include "net/base/upload_progress.h" | |
21 #include "net/cookies/canonical_cookie.h" | |
22 #include "net/url_request/redirect_info.h" | |
23 #include "net/url_request/url_request.h" | |
24 #include "url/gurl.h" | |
25 | |
26 namespace net { | |
27 | |
28 class AuthChallengeInfo; | |
29 class AuthCredentials; | |
30 class CookieOptions; | |
31 class CookieStore; | |
32 class Filter; | |
33 class HttpRequestHeaders; | |
34 class HttpResponseInfo; | |
35 class IOBuffer; | |
36 struct LoadTimingInfo; | |
37 class NetworkDelegate; | |
38 class SSLCertRequestInfo; | |
39 class SSLInfo; | |
40 class UploadDataStream; | |
41 class URLRequestStatus; | |
42 class X509Certificate; | |
43 | |
44 class NET_EXPORT URLRequestJob | |
45 : public base::RefCounted<URLRequestJob>, | |
46 public base::PowerObserver { | |
47 public: | |
48 explicit URLRequestJob(URLRequest* request, | |
49 NetworkDelegate* network_delegate); | |
50 | |
51 // Returns the request that owns this job. THIS POINTER MAY BE NULL if the | |
52 // request was destroyed. | |
53 URLRequest* request() const { | |
54 return request_; | |
55 } | |
56 | |
57 // Sets the upload data, most requests have no upload data, so this is a NOP. | |
58 // Job types supporting upload data will override this. | |
59 virtual void SetUpload(UploadDataStream* upload_data_stream); | |
60 | |
61 // Sets extra request headers for Job types that support request | |
62 // headers. Called once before Start() is called. | |
63 virtual void SetExtraRequestHeaders(const HttpRequestHeaders& headers); | |
64 | |
65 // Sets the priority of the job. Called once before Start() is | |
66 // called, but also when the priority of the parent request changes. | |
67 virtual void SetPriority(RequestPriority priority); | |
68 | |
69 // If any error occurs while starting the Job, NotifyStartError should be | |
70 // called. | |
71 // This helps ensure that all errors follow more similar notification code | |
72 // paths, which should simplify testing. | |
73 virtual void Start() = 0; | |
74 | |
75 // This function MUST somehow call NotifyDone/NotifyCanceled or some requests | |
76 // will get leaked. Certain callers use that message to know when they can | |
77 // delete their URLRequest object, even when doing a cancel. The default | |
78 // Kill implementation calls NotifyCanceled, so it is recommended that | |
79 // subclasses call URLRequestJob::Kill() after doing any additional work. | |
80 // | |
81 // The job should endeavor to stop working as soon as is convenient, but must | |
82 // not send and complete notifications from inside this function. Instead, | |
83 // complete notifications (including "canceled") should be sent from a | |
84 // callback run from the message loop. | |
85 // | |
86 // The job is not obliged to immediately stop sending data in response to | |
87 // this call, nor is it obliged to fail with "canceled" unless not all data | |
88 // was sent as a result. A typical case would be where the job is almost | |
89 // complete and can succeed before the canceled notification can be | |
90 // dispatched (from the message loop). | |
91 // | |
92 // The job should be prepared to receive multiple calls to kill it, but only | |
93 // one notification must be issued. | |
94 virtual void Kill(); | |
95 | |
96 // Called to detach the request from this Job. Results in the Job being | |
97 // killed off eventually. The job must not use the request pointer any more. | |
98 void DetachRequest(); | |
99 | |
100 // Called to read post-filtered data from this Job, returning the number of | |
101 // bytes read, 0 when there is no more data, or -1 if there was an error. | |
102 // This is just the backend for URLRequest::Read, see that function for | |
103 // more info. | |
104 bool Read(IOBuffer* buf, int buf_size, int* bytes_read); | |
105 | |
106 // Stops further caching of this request, if any. For more info, see | |
107 // URLRequest::StopCaching(). | |
108 virtual void StopCaching(); | |
109 | |
110 virtual bool GetFullRequestHeaders(HttpRequestHeaders* headers) const; | |
111 | |
112 // Get the number of bytes received from network. | |
113 virtual int64 GetTotalReceivedBytes() const; | |
114 | |
115 // Called to fetch the current load state for the job. | |
116 virtual LoadState GetLoadState() const; | |
117 | |
118 // Called to get the upload progress in bytes. | |
119 virtual UploadProgress GetUploadProgress() const; | |
120 | |
121 // Called to fetch the charset for this request. Only makes sense for some | |
122 // types of requests. Returns true on success. Calling this on a type that | |
123 // doesn't have a charset will return false. | |
124 virtual bool GetCharset(std::string* charset); | |
125 | |
126 // Called to get response info. | |
127 virtual void GetResponseInfo(HttpResponseInfo* info); | |
128 | |
129 // This returns the times when events actually occurred, rather than the time | |
130 // each event blocked the request. See FixupLoadTimingInfo in url_request.h | |
131 // for more information on the difference. | |
132 virtual void GetLoadTimingInfo(LoadTimingInfo* load_timing_info) const; | |
133 | |
134 // Returns the cookie values included in the response, if applicable. | |
135 // Returns true if applicable. | |
136 // NOTE: This removes the cookies from the job, so it will only return | |
137 // useful results once per job. | |
138 virtual bool GetResponseCookies(std::vector<std::string>* cookies); | |
139 | |
140 // Called to setup a stream filter for this request. An example of filter is | |
141 // content encoding/decoding. | |
142 // Subclasses should return the appropriate Filter, or NULL for no Filter. | |
143 // This class takes ownership of the returned Filter. | |
144 // | |
145 // The default implementation returns NULL. | |
146 virtual Filter* SetupFilter() const; | |
147 | |
148 // Called to determine if this response is a redirect. Only makes sense | |
149 // for some types of requests. This method returns true if the response | |
150 // is a redirect, and fills in the location param with the URL of the | |
151 // redirect. The HTTP status code (e.g., 302) is filled into | |
152 // |*http_status_code| to signify the type of redirect. | |
153 // | |
154 // The caller is responsible for following the redirect by setting up an | |
155 // appropriate replacement Job. Note that the redirected location may be | |
156 // invalid, the caller should be sure it can handle this. | |
157 // | |
158 // The default implementation inspects the response_info_. | |
159 virtual bool IsRedirectResponse(GURL* location, int* http_status_code); | |
160 | |
161 // Called to determine if it is okay to copy the reference fragment from the | |
162 // original URL (if existent) to the redirection target when the redirection | |
163 // target has no reference fragment. | |
164 // | |
165 // The default implementation returns true. | |
166 virtual bool CopyFragmentOnRedirect(const GURL& location) const; | |
167 | |
168 // Called to determine if it is okay to redirect this job to the specified | |
169 // location. This may be used to implement protocol-specific restrictions. | |
170 // If this function returns false, then the URLRequest will fail | |
171 // reporting ERR_UNSAFE_REDIRECT. | |
172 virtual bool IsSafeRedirect(const GURL& location); | |
173 | |
174 // Called to determine if this response is asking for authentication. Only | |
175 // makes sense for some types of requests. The caller is responsible for | |
176 // obtaining the credentials passing them to SetAuth. | |
177 virtual bool NeedsAuth(); | |
178 | |
179 // Fills the authentication info with the server's response. | |
180 virtual void GetAuthChallengeInfo( | |
181 scoped_refptr<AuthChallengeInfo>* auth_info); | |
182 | |
183 // Resend the request with authentication credentials. | |
184 virtual void SetAuth(const AuthCredentials& credentials); | |
185 | |
186 // Display the error page without asking for credentials again. | |
187 virtual void CancelAuth(); | |
188 | |
189 virtual void ContinueWithCertificate(X509Certificate* client_cert); | |
190 | |
191 // Continue processing the request ignoring the last error. | |
192 virtual void ContinueDespiteLastError(); | |
193 | |
194 // Continue with the network request. | |
195 virtual void ResumeNetworkStart(); | |
196 | |
197 void FollowDeferredRedirect(); | |
198 | |
199 // Returns true if the Job is done producing response data and has called | |
200 // NotifyDone on the request. | |
201 bool is_done() const { return done_; } | |
202 | |
203 // Get/Set expected content size | |
204 int64 expected_content_size() const { return expected_content_size_; } | |
205 void set_expected_content_size(const int64& size) { | |
206 expected_content_size_ = size; | |
207 } | |
208 | |
209 // Whether we have processed the response for that request yet. | |
210 bool has_response_started() const { return has_handled_response_; } | |
211 | |
212 // These methods are not applicable to all connections. | |
213 virtual bool GetMimeType(std::string* mime_type) const; | |
214 virtual int GetResponseCode() const; | |
215 | |
216 // Returns the socket address for the connection. | |
217 // See url_request.h for details. | |
218 virtual HostPortPair GetSocketAddress() const; | |
219 | |
220 // base::PowerObserver methods: | |
221 // We invoke URLRequestJob::Kill on suspend (crbug.com/4606). | |
222 void OnSuspend() override; | |
223 | |
224 // Called after a NetworkDelegate has been informed that the URLRequest | |
225 // will be destroyed. This is used to track that no pending callbacks | |
226 // exist at destruction time of the URLRequestJob, unless they have been | |
227 // canceled by an explicit NetworkDelegate::NotifyURLRequestDestroyed() call. | |
228 virtual void NotifyURLRequestDestroyed(); | |
229 | |
230 // Given |policy|, |referrer|, and |redirect_destination|, returns the | |
231 // referrer URL mandated by |request|'s referrer policy. | |
232 static GURL ComputeReferrerForRedirect(URLRequest::ReferrerPolicy policy, | |
233 const std::string& referrer, | |
234 const GURL& redirect_destination); | |
235 | |
236 protected: | |
237 friend class base::RefCounted<URLRequestJob>; | |
238 ~URLRequestJob() override; | |
239 | |
240 // Notifies the job that a certificate is requested. | |
241 void NotifyCertificateRequested(SSLCertRequestInfo* cert_request_info); | |
242 | |
243 // Notifies the job about an SSL certificate error. | |
244 void NotifySSLCertificateError(const SSLInfo& ssl_info, bool fatal); | |
245 | |
246 // Delegates to URLRequest::Delegate. | |
247 bool CanGetCookies(const CookieList& cookie_list) const; | |
248 | |
249 // Delegates to URLRequest::Delegate. | |
250 bool CanSetCookie(const std::string& cookie_line, | |
251 CookieOptions* options) const; | |
252 | |
253 // Delegates to URLRequest::Delegate. | |
254 bool CanEnablePrivacyMode() const; | |
255 | |
256 // Returns the cookie store to be used for the request. | |
257 CookieStore* GetCookieStore() const; | |
258 | |
259 // Notifies the job that the network is about to be used. | |
260 void NotifyBeforeNetworkStart(bool* defer); | |
261 | |
262 // Notifies the job that headers have been received. | |
263 void NotifyHeadersComplete(); | |
264 | |
265 // Notifies the request that the job has completed a Read operation. | |
266 void NotifyReadComplete(int bytes_read); | |
267 | |
268 // Notifies the request that a start error has occurred. | |
269 void NotifyStartError(const URLRequestStatus& status); | |
270 | |
271 // NotifyDone marks when we are done with a request. It is really | |
272 // a glorified set_status, but also does internal state checking and | |
273 // job tracking. It should be called once per request, when the job is | |
274 // finished doing all IO. | |
275 void NotifyDone(const URLRequestStatus& status); | |
276 | |
277 // Some work performed by NotifyDone must be completed on a separate task | |
278 // so as to avoid re-entering the delegate. This method exists to perform | |
279 // that work. | |
280 void CompleteNotifyDone(); | |
281 | |
282 // Used as an asynchronous callback for Kill to notify the URLRequest | |
283 // that we were canceled. | |
284 void NotifyCanceled(); | |
285 | |
286 // Notifies the job the request should be restarted. | |
287 // Should only be called if the job has not started a response. | |
288 void NotifyRestartRequired(); | |
289 | |
290 // See corresponding functions in url_request.h. | |
291 void OnCallToDelegate(); | |
292 void OnCallToDelegateComplete(); | |
293 | |
294 // Called to read raw (pre-filtered) data from this Job. | |
295 // If returning true, data was read from the job. buf will contain | |
296 // the data, and bytes_read will receive the number of bytes read. | |
297 // If returning true, and bytes_read is returned as 0, there is no | |
298 // additional data to be read. | |
299 // If returning false, an error occurred or an async IO is now pending. | |
300 // If async IO is pending, the status of the request will be | |
301 // URLRequestStatus::IO_PENDING, and buf must remain available until the | |
302 // operation is completed. See comments on URLRequest::Read for more | |
303 // info. | |
304 virtual bool ReadRawData(IOBuffer* buf, int buf_size, int *bytes_read); | |
305 | |
306 // Called to tell the job that a filter has successfully reached the end of | |
307 // the stream. | |
308 virtual void DoneReading(); | |
309 | |
310 // Called to tell the job that the body won't be read because it's a redirect. | |
311 // This is needed so that redirect headers can be cached even though their | |
312 // bodies are never read. | |
313 virtual void DoneReadingRedirectResponse(); | |
314 | |
315 // Informs the filter that data has been read into its buffer | |
316 void FilteredDataRead(int bytes_read); | |
317 | |
318 // Reads filtered data from the request. Returns true if successful, | |
319 // false otherwise. Note, if there is not enough data received to | |
320 // return data, this call can issue a new async IO request under | |
321 // the hood. | |
322 bool ReadFilteredData(int *bytes_read); | |
323 | |
324 // Whether the response is being filtered in this job. | |
325 // Only valid after NotifyHeadersComplete() has been called. | |
326 bool HasFilter() { return filter_ != NULL; } | |
327 | |
328 // At or near destruction time, a derived class may request that the filters | |
329 // be destroyed so that statistics can be gathered while the derived class is | |
330 // still present to assist in calculations. This is used by URLRequestHttpJob | |
331 // to get SDCH to emit stats. | |
332 void DestroyFilters(); | |
333 | |
334 // Provides derived classes with access to the request's network delegate. | |
335 NetworkDelegate* network_delegate() { return network_delegate_; } | |
336 | |
337 // The status of the job. | |
338 const URLRequestStatus GetStatus(); | |
339 | |
340 // Set the status of the job. | |
341 void SetStatus(const URLRequestStatus& status); | |
342 | |
343 // Set the proxy server that was used, if any. | |
344 void SetProxyServer(const HostPortPair& proxy_server); | |
345 | |
346 // The number of bytes read before passing to the filter. | |
347 int prefilter_bytes_read() const { return prefilter_bytes_read_; } | |
348 | |
349 // The number of bytes read after passing through the filter. | |
350 int postfilter_bytes_read() const { return postfilter_bytes_read_; } | |
351 | |
352 // Total number of bytes read from network (or cache) and typically handed | |
353 // to filter to process. Used to histogram compression ratios, and error | |
354 // recovery scenarios in filters. | |
355 int64 filter_input_byte_count() const { return filter_input_byte_count_; } | |
356 | |
357 // The request that initiated this job. This value MAY BE NULL if the | |
358 // request was released by DetachRequest(). | |
359 URLRequest* request_; | |
360 | |
361 private: | |
362 // When data filtering is enabled, this function is used to read data | |
363 // for the filter. Returns true if raw data was read. Returns false if | |
364 // an error occurred (or we are waiting for IO to complete). | |
365 bool ReadRawDataForFilter(int *bytes_read); | |
366 | |
367 // Invokes ReadRawData and records bytes read if the read completes | |
368 // synchronously. | |
369 bool ReadRawDataHelper(IOBuffer* buf, int buf_size, int* bytes_read); | |
370 | |
371 // Called in response to a redirect that was not canceled to follow the | |
372 // redirect. The current job will be replaced with a new job loading the | |
373 // given redirect destination. | |
374 void FollowRedirect(const RedirectInfo& redirect_info); | |
375 | |
376 // Called after every raw read. If |bytes_read| is > 0, this indicates | |
377 // a successful read of |bytes_read| unfiltered bytes. If |bytes_read| | |
378 // is 0, this indicates that there is no additional data to read. If | |
379 // |bytes_read| is < 0, an error occurred and no bytes were read. | |
380 void OnRawReadComplete(int bytes_read); | |
381 | |
382 // Updates the profiling info and notifies observers that an additional | |
383 // |bytes_read| unfiltered bytes have been read for this job. | |
384 void RecordBytesRead(int bytes_read); | |
385 | |
386 // Called to query whether there is data available in the filter to be read | |
387 // out. | |
388 bool FilterHasData(); | |
389 | |
390 // Subclasses may implement this method to record packet arrival times. | |
391 // The default implementation does nothing. | |
392 virtual void UpdatePacketReadTimes(); | |
393 | |
394 // Computes a new RedirectInfo based on receiving a redirect response of | |
395 // |location| and |http_status_code|. | |
396 RedirectInfo ComputeRedirectInfo(const GURL& location, int http_status_code); | |
397 | |
398 // Indicates that the job is done producing data, either it has completed | |
399 // all the data or an error has been encountered. Set exclusively by | |
400 // NotifyDone so that it is kept in sync with the request. | |
401 bool done_; | |
402 | |
403 int prefilter_bytes_read_; | |
404 int postfilter_bytes_read_; | |
405 int64 filter_input_byte_count_; | |
406 | |
407 // The data stream filter which is enabled on demand. | |
408 scoped_ptr<Filter> filter_; | |
409 | |
410 // If the filter filled its output buffer, then there is a change that it | |
411 // still has internal data to emit, and this flag is set. | |
412 bool filter_needs_more_output_space_; | |
413 | |
414 // When we filter data, we receive data into the filter buffers. After | |
415 // processing the filtered data, we return the data in the caller's buffer. | |
416 // While the async IO is in progress, we save the user buffer here, and | |
417 // when the IO completes, we fill this in. | |
418 scoped_refptr<IOBuffer> filtered_read_buffer_; | |
419 int filtered_read_buffer_len_; | |
420 | |
421 // We keep a pointer to the read buffer while asynchronous reads are | |
422 // in progress, so we are able to pass those bytes to job observers. | |
423 scoped_refptr<IOBuffer> raw_read_buffer_; | |
424 | |
425 // Used by HandleResponseIfNecessary to track whether we've sent the | |
426 // OnResponseStarted callback and potentially redirect callbacks as well. | |
427 bool has_handled_response_; | |
428 | |
429 // Expected content size | |
430 int64 expected_content_size_; | |
431 | |
432 // Set when a redirect is deferred. | |
433 RedirectInfo deferred_redirect_info_; | |
434 | |
435 // The network delegate to use with this request, if any. | |
436 NetworkDelegate* network_delegate_; | |
437 | |
438 base::WeakPtrFactory<URLRequestJob> weak_factory_; | |
439 | |
440 DISALLOW_COPY_AND_ASSIGN(URLRequestJob); | |
441 }; | |
442 | |
443 } // namespace net | |
444 | |
445 #endif // NET_URL_REQUEST_URL_REQUEST_JOB_H_ | |
OLD | NEW |