Fix nullptr crash in OnEmbed
[chromium-blink-merge.git] / net / http / http_cache_transaction.h
blobec88da37e1416febc51c03d538ea5a0af79d2d0a
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 // This file declares HttpCache::Transaction, a private class of HttpCache so
6 // it should only be included by http_cache.cc
8 #ifndef NET_HTTP_HTTP_CACHE_TRANSACTION_H_
9 #define NET_HTTP_HTTP_CACHE_TRANSACTION_H_
11 #include <stddef.h>
13 #include <string>
15 #include "base/basictypes.h"
16 #include "base/memory/ref_counted.h"
17 #include "base/memory/scoped_ptr.h"
18 #include "base/memory/weak_ptr.h"
19 #include "base/time/time.h"
20 #include "net/base/completion_callback.h"
21 #include "net/base/io_buffer.h"
22 #include "net/base/load_states.h"
23 #include "net/base/request_priority.h"
24 #include "net/base/upload_progress.h"
25 #include "net/http/http_cache.h"
26 #include "net/http/http_request_headers.h"
27 #include "net/http/http_response_headers.h"
28 #include "net/http/http_response_info.h"
29 #include "net/http/http_transaction.h"
30 #include "net/http/partial_data.h"
31 #include "net/log/net_log.h"
32 #include "net/socket/connection_attempts.h"
33 #include "net/websockets/websocket_handshake_stream_base.h"
35 namespace net {
37 class PartialData;
38 struct HttpRequestInfo;
39 struct LoadTimingInfo;
41 // This is the transaction that is returned by the HttpCache transaction
42 // factory.
43 class HttpCache::Transaction : public HttpTransaction {
44 public:
45 // The transaction has the following modes, which apply to how it may access
46 // its cache entry.
48 // o If the mode of the transaction is NONE, then it is in "pass through"
49 // mode and all methods just forward to the inner network transaction.
51 // o If the mode of the transaction is only READ, then it may only read from
52 // the cache entry.
54 // o If the mode of the transaction is only WRITE, then it may only write to
55 // the cache entry.
57 // o If the mode of the transaction is READ_WRITE, then the transaction may
58 // optionally modify the cache entry (e.g., possibly corresponding to
59 // cache validation).
61 // o If the mode of the transaction is UPDATE, then the transaction may
62 // update existing cache entries, but will never create a new entry or
63 // respond using the entry read from the cache.
64 enum Mode {
65 NONE = 0,
66 READ_META = 1 << 0,
67 READ_DATA = 1 << 1,
68 READ = READ_META | READ_DATA,
69 WRITE = 1 << 2,
70 READ_WRITE = READ | WRITE,
71 UPDATE = READ_META | WRITE, // READ_WRITE & ~READ_DATA
74 Transaction(RequestPriority priority,
75 HttpCache* cache);
76 ~Transaction() override;
78 Mode mode() const { return mode_; }
80 const std::string& key() const { return cache_key_; }
82 // Writes |buf_len| bytes of meta-data from the provided buffer |buf|. to the
83 // HTTP cache entry that backs this transaction (if any).
84 // Returns the number of bytes actually written, or a net error code. If the
85 // operation cannot complete immediately, returns ERR_IO_PENDING, grabs a
86 // reference to the buffer (until completion), and notifies the caller using
87 // the provided |callback| when the operation finishes.
89 // The first time this method is called for a given transaction, previous
90 // meta-data will be overwritten with the provided data, and subsequent
91 // invocations will keep appending to the cached entry.
93 // In order to guarantee that the metadata is set to the correct entry, the
94 // response (or response info) must be evaluated by the caller, for instance
95 // to make sure that the response_time is as expected, before calling this
96 // method.
97 int WriteMetadata(IOBuffer* buf,
98 int buf_len,
99 const CompletionCallback& callback);
101 // This transaction is being deleted and we are not done writing to the cache.
102 // We need to indicate that the response data was truncated. Returns true on
103 // success. Keep in mind that this operation may have side effects, such as
104 // deleting the active entry.
105 bool AddTruncatedFlag();
107 HttpCache::ActiveEntry* entry() { return entry_; }
109 // Returns the LoadState of the writer transaction of a given ActiveEntry. In
110 // other words, returns the LoadState of this transaction without asking the
111 // http cache, because this transaction should be the one currently writing
112 // to the cache entry.
113 LoadState GetWriterLoadState() const;
115 const CompletionCallback& io_callback() { return io_callback_; }
117 const BoundNetLog& net_log() const;
119 // Bypasses the cache lock whenever there is lock contention.
120 void BypassLockForTest() {
121 bypass_lock_for_test_ = true;
124 // Generates a failure when attempting to conditionalize a network request.
125 void FailConditionalizationForTest() {
126 fail_conditionalization_for_test_ = true;
129 // HttpTransaction methods:
130 int Start(const HttpRequestInfo* request_info,
131 const CompletionCallback& callback,
132 const BoundNetLog& net_log) override;
133 int RestartIgnoringLastError(const CompletionCallback& callback) override;
134 int RestartWithCertificate(X509Certificate* client_cert,
135 const CompletionCallback& callback) override;
136 int RestartWithAuth(const AuthCredentials& credentials,
137 const CompletionCallback& callback) override;
138 bool IsReadyToRestartForAuth() override;
139 int Read(IOBuffer* buf,
140 int buf_len,
141 const CompletionCallback& callback) override;
142 void StopCaching() override;
143 bool GetFullRequestHeaders(HttpRequestHeaders* headers) const override;
144 int64 GetTotalReceivedBytes() const override;
145 void DoneReading() override;
146 const HttpResponseInfo* GetResponseInfo() const override;
147 LoadState GetLoadState() const override;
148 UploadProgress GetUploadProgress(void) const override;
149 void SetQuicServerInfo(QuicServerInfo* quic_server_info) override;
150 bool GetLoadTimingInfo(LoadTimingInfo* load_timing_info) const override;
151 void SetPriority(RequestPriority priority) override;
152 void SetWebSocketHandshakeStreamCreateHelper(
153 WebSocketHandshakeStreamBase::CreateHelper* create_helper) override;
154 void SetBeforeNetworkStartCallback(
155 const BeforeNetworkStartCallback& callback) override;
156 void SetBeforeProxyHeadersSentCallback(
157 const BeforeProxyHeadersSentCallback& callback) override;
158 int ResumeNetworkStart() override;
159 void GetConnectionAttempts(ConnectionAttempts* out) const override;
161 private:
162 static const size_t kNumValidationHeaders = 2;
163 // Helper struct to pair a header name with its value, for
164 // headers used to validate cache entries.
165 struct ValidationHeaders {
166 ValidationHeaders() : initialized(false) {}
168 std::string values[kNumValidationHeaders];
169 bool initialized;
172 enum State {
173 // Normally, states are traversed in approximately this order.
174 STATE_NONE,
175 STATE_GET_BACKEND,
176 STATE_GET_BACKEND_COMPLETE,
177 STATE_INIT_ENTRY,
178 STATE_OPEN_ENTRY,
179 STATE_OPEN_ENTRY_COMPLETE,
180 STATE_DOOM_ENTRY,
181 STATE_DOOM_ENTRY_COMPLETE,
182 STATE_CREATE_ENTRY,
183 STATE_CREATE_ENTRY_COMPLETE,
184 STATE_ADD_TO_ENTRY,
185 STATE_ADD_TO_ENTRY_COMPLETE,
186 STATE_CACHE_READ_RESPONSE,
187 STATE_CACHE_READ_RESPONSE_COMPLETE,
188 STATE_TOGGLE_UNUSED_SINCE_PREFETCH,
189 STATE_TOGGLE_UNUSED_SINCE_PREFETCH_COMPLETE,
190 STATE_CACHE_DISPATCH_VALIDATION,
191 STATE_CACHE_QUERY_DATA,
192 STATE_CACHE_QUERY_DATA_COMPLETE,
193 STATE_START_PARTIAL_CACHE_VALIDATION,
194 STATE_COMPLETE_PARTIAL_CACHE_VALIDATION,
195 STATE_SEND_REQUEST,
196 STATE_SEND_REQUEST_COMPLETE,
197 STATE_SUCCESSFUL_SEND_REQUEST,
198 STATE_UPDATE_CACHED_RESPONSE,
199 STATE_CACHE_WRITE_UPDATED_RESPONSE,
200 STATE_CACHE_WRITE_UPDATED_RESPONSE_COMPLETE,
201 STATE_UPDATE_CACHED_RESPONSE_COMPLETE,
202 STATE_OVERWRITE_CACHED_RESPONSE,
203 STATE_CACHE_WRITE_RESPONSE,
204 STATE_CACHE_WRITE_RESPONSE_COMPLETE,
205 STATE_TRUNCATE_CACHED_DATA,
206 STATE_TRUNCATE_CACHED_DATA_COMPLETE,
207 STATE_TRUNCATE_CACHED_METADATA,
208 STATE_TRUNCATE_CACHED_METADATA_COMPLETE,
209 STATE_PARTIAL_HEADERS_RECEIVED,
210 STATE_CACHE_READ_METADATA,
211 STATE_CACHE_READ_METADATA_COMPLETE,
213 // These states are entered from Read/AddTruncatedFlag.
214 STATE_NETWORK_READ,
215 STATE_NETWORK_READ_COMPLETE,
216 STATE_CACHE_READ_DATA,
217 STATE_CACHE_READ_DATA_COMPLETE,
218 STATE_CACHE_WRITE_DATA,
219 STATE_CACHE_WRITE_DATA_COMPLETE,
220 STATE_CACHE_WRITE_TRUNCATED_RESPONSE,
221 STATE_CACHE_WRITE_TRUNCATED_RESPONSE_COMPLETE
224 // Used for categorizing transactions for reporting in histograms. Patterns
225 // cover relatively common use cases being measured and considered for
226 // optimization. Many use cases that are more complex or uncommon are binned
227 // as PATTERN_NOT_COVERED, and details are not reported.
228 // NOTE: This enumeration is used in histograms, so please do not add entries
229 // in the middle.
230 enum TransactionPattern {
231 PATTERN_UNDEFINED,
232 PATTERN_NOT_COVERED,
233 PATTERN_ENTRY_NOT_CACHED,
234 PATTERN_ENTRY_USED,
235 PATTERN_ENTRY_VALIDATED,
236 PATTERN_ENTRY_UPDATED,
237 PATTERN_ENTRY_CANT_CONDITIONALIZE,
238 PATTERN_MAX,
241 // Runs the state transition loop. Resets and calls |callback_| on exit,
242 // unless the return value is ERR_IO_PENDING.
243 int DoLoop(int result);
245 // Each of these methods corresponds to a State value. If there is an
246 // argument, the value corresponds to the return of the previous state or
247 // corresponding callback.
248 int DoGetBackend();
249 int DoGetBackendComplete(int result);
250 int DoInitEntry();
251 int DoOpenEntry();
252 int DoOpenEntryComplete(int result);
253 int DoDoomEntry();
254 int DoDoomEntryComplete(int result);
255 int DoCreateEntry();
256 int DoCreateEntryComplete(int result);
257 int DoAddToEntry();
258 int DoAddToEntryComplete(int result);
259 int DoCacheReadResponse();
260 int DoCacheReadResponseComplete(int result);
261 int DoCacheToggleUnusedSincePrefetch();
262 int DoCacheToggleUnusedSincePrefetchComplete(int result);
263 int DoCacheDispatchValidation();
264 int DoCacheQueryData();
265 int DoCacheQueryDataComplete(int result);
266 int DoStartPartialCacheValidation();
267 int DoCompletePartialCacheValidation(int result);
268 int DoSendRequest();
269 int DoSendRequestComplete(int result);
270 int DoSuccessfulSendRequest();
271 int DoUpdateCachedResponse();
272 int DoCacheWriteUpdatedResponse();
273 int DoCacheWriteUpdatedResponseComplete(int result);
274 int DoUpdateCachedResponseComplete(int result);
275 int DoOverwriteCachedResponse();
276 int DoCacheWriteResponse();
277 int DoCacheWriteResponseComplete(int result);
278 int DoTruncateCachedData();
279 int DoTruncateCachedDataComplete(int result);
280 int DoTruncateCachedMetadata();
281 int DoTruncateCachedMetadataComplete(int result);
282 int DoPartialHeadersReceived();
283 int DoCacheReadMetadata();
284 int DoCacheReadMetadataComplete(int result);
285 int DoNetworkRead();
286 int DoNetworkReadComplete(int result);
287 int DoCacheReadData();
288 int DoCacheReadDataComplete(int result);
289 int DoCacheWriteData(int num_bytes);
290 int DoCacheWriteDataComplete(int result);
291 int DoCacheWriteTruncatedResponse();
292 int DoCacheWriteTruncatedResponseComplete(int result);
294 // These functions are involved in a field trial testing storing certificates
295 // in seperate entries from the HttpResponseInfo.
296 void ReadCertChain();
297 void WriteCertChain();
299 // Sets request_ and fields derived from it.
300 void SetRequest(const BoundNetLog& net_log, const HttpRequestInfo* request);
302 // Returns true if the request should be handled exclusively by the network
303 // layer (skipping the cache entirely).
304 bool ShouldPassThrough();
306 // Called to begin reading from the cache. Returns network error code.
307 int BeginCacheRead();
309 // Called to begin validating the cache entry. Returns network error code.
310 int BeginCacheValidation();
312 // Called to begin validating an entry that stores partial content. Returns
313 // a network error code.
314 int BeginPartialCacheValidation();
316 // Validates the entry headers against the requested range and continues with
317 // the validation of the rest of the entry. Returns a network error code.
318 int ValidateEntryHeadersAndContinue();
320 // Called to start requests which were given an "if-modified-since" or
321 // "if-none-match" validation header by the caller (NOT when the request was
322 // conditionalized internally in response to LOAD_VALIDATE_CACHE).
323 // Returns a network error code.
324 int BeginExternallyConditionalizedRequest();
326 // Called to restart a network transaction after an error. Returns network
327 // error code.
328 int RestartNetworkRequest();
330 // Called to restart a network transaction with a client certificate.
331 // Returns network error code.
332 int RestartNetworkRequestWithCertificate(X509Certificate* client_cert);
334 // Called to restart a network transaction with authentication credentials.
335 // Returns network error code.
336 int RestartNetworkRequestWithAuth(const AuthCredentials& credentials);
338 // Called to determine if we need to validate the cache entry before using it,
339 // and whether the validation should be synchronous or asynchronous.
340 ValidationType RequiresValidation();
342 // Called to make the request conditional (to ask the server if the cached
343 // copy is valid). Returns true if able to make the request conditional.
344 bool ConditionalizeRequest();
346 // Makes sure that a 206 response is expected. Returns true on success.
347 // On success, handling_206_ will be set to true if we are processing a
348 // partial entry.
349 bool ValidatePartialResponse();
351 // Handles a response validation error by bypassing the cache.
352 void IgnoreRangeRequest();
354 // Fixes the response headers to match expectations for a HEAD request.
355 void FixHeadersForHead();
357 // Setups the transaction for reading from the cache entry.
358 int SetupEntryForRead();
360 // Called to write data to the cache entry. If the write fails, then the
361 // cache entry is destroyed. Future calls to this function will just do
362 // nothing without side-effect. Returns a network error code.
363 int WriteToEntry(int index, int offset, IOBuffer* data, int data_len,
364 const CompletionCallback& callback);
366 // Called to write response_ to the cache entry. |truncated| indicates if the
367 // entry should be marked as incomplete.
368 int WriteResponseInfoToEntry(bool truncated);
370 // Helper function, should be called with result of WriteResponseInfoToEntry
371 // (or the result of the callback, when WriteResponseInfoToEntry returns
372 // ERR_IO_PENDING). Calls DoneWritingToEntry if |result| is not the right
373 // number of bytes. It is expected that the state that calls this will
374 // return whatever net error code this function returns, which currently
375 // is always "OK".
376 int OnWriteResponseInfoToEntryComplete(int result);
378 // Called when we are done writing to the cache entry.
379 void DoneWritingToEntry(bool success);
381 // Returns an error to signal the caller that the current read failed. The
382 // current operation |result| is also logged. If |restart| is true, the
383 // transaction should be restarted.
384 int OnCacheReadError(int result, bool restart);
386 // Called when the cache lock timeout fires.
387 void OnAddToEntryTimeout(base::TimeTicks start_time);
389 // Deletes the current partial cache entry (sparse), and optionally removes
390 // the control object (partial_).
391 void DoomPartialEntry(bool delete_object);
393 // Performs the needed work after receiving data from the network, when
394 // working with range requests.
395 int DoPartialNetworkReadCompleted(int result);
397 // Performs the needed work after receiving data from the cache, when
398 // working with range requests.
399 int DoPartialCacheReadCompleted(int result);
401 // Restarts this transaction after deleting the cached data. It is meant to
402 // be used when the current request cannot be fulfilled due to conflicts
403 // between the byte range request and the cached entry.
404 int DoRestartPartialRequest();
406 // Resets the relavant internal state to remove traces of internal processing
407 // related to range requests. Deletes |partial_| if |delete_object| is true.
408 void ResetPartialState(bool delete_object);
410 // Resets |network_trans_|, which must be non-NULL. Also updates
411 // |old_network_trans_load_timing_|, which must be NULL when this is called.
412 void ResetNetworkTransaction();
414 // Returns true if we should bother attempting to resume this request if it
415 // is aborted while in progress. If |has_data| is true, the size of the stored
416 // data is considered for the result.
417 bool CanResume(bool has_data);
419 void UpdateTransactionPattern(TransactionPattern new_transaction_pattern);
420 void RecordHistograms();
422 // Called to signal completion of asynchronous IO.
423 void OnIOComplete(int result);
425 State next_state_;
426 const HttpRequestInfo* request_;
427 RequestPriority priority_;
428 BoundNetLog net_log_;
429 scoped_ptr<HttpRequestInfo> custom_request_;
430 HttpRequestHeaders request_headers_copy_;
431 // If extra_headers specified a "if-modified-since" or "if-none-match",
432 // |external_validation_| contains the value of those headers.
433 ValidationHeaders external_validation_;
434 base::WeakPtr<HttpCache> cache_;
435 HttpCache::ActiveEntry* entry_;
436 HttpCache::ActiveEntry* new_entry_;
437 scoped_ptr<HttpTransaction> network_trans_;
438 CompletionCallback callback_; // Consumer's callback.
439 HttpResponseInfo response_;
440 HttpResponseInfo auth_response_;
441 const HttpResponseInfo* new_response_;
442 std::string cache_key_;
443 Mode mode_;
444 bool reading_; // We are already reading. Never reverts to false once set.
445 bool invalid_range_; // We may bypass the cache for this request.
446 bool truncated_; // We don't have all the response data.
447 bool is_sparse_; // The data is stored in sparse byte ranges.
448 bool range_requested_; // The user requested a byte range.
449 bool handling_206_; // We must deal with this 206 response.
450 bool cache_pending_; // We are waiting for the HttpCache.
451 bool done_reading_; // All available data was read.
452 bool vary_mismatch_; // The request doesn't match the stored vary data.
453 bool couldnt_conditionalize_request_;
454 bool bypass_lock_for_test_; // A test is exercising the cache lock.
455 bool fail_conditionalization_for_test_; // Fail ConditionalizeRequest.
456 scoped_refptr<IOBuffer> read_buf_;
457 int io_buf_len_;
458 int read_offset_;
459 int effective_load_flags_;
460 int write_len_;
461 scoped_ptr<PartialData> partial_; // We are dealing with range requests.
462 UploadProgress final_upload_progress_;
463 CompletionCallback io_callback_;
465 // Members used to track data for histograms.
466 TransactionPattern transaction_pattern_;
467 base::TimeTicks entry_lock_waiting_since_;
468 base::TimeTicks first_cache_access_since_;
469 base::TimeTicks send_request_since_;
471 int64 total_received_bytes_;
473 // Load timing information for the last network request, if any. Set in the
474 // 304 and 206 response cases, as the network transaction may be destroyed
475 // before the caller requests load timing information.
476 scoped_ptr<LoadTimingInfo> old_network_trans_load_timing_;
478 ConnectionAttempts old_connection_attempts_;
480 // The helper object to use to create WebSocketHandshakeStreamBase
481 // objects. Only relevant when establishing a WebSocket connection.
482 // This is passed to the underlying network transaction. It is stored here in
483 // case the transaction does not exist yet.
484 WebSocketHandshakeStreamBase::CreateHelper*
485 websocket_handshake_stream_base_create_helper_;
487 BeforeNetworkStartCallback before_network_start_callback_;
488 BeforeProxyHeadersSentCallback before_proxy_headers_sent_callback_;
490 base::WeakPtrFactory<Transaction> weak_factory_;
492 DISALLOW_COPY_AND_ASSIGN(Transaction);
495 } // namespace net
497 #endif // NET_HTTP_HTTP_CACHE_TRANSACTION_H_