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 #include "net/http/http_cache_transaction.h"
7 #include "build/build_config.h"
16 #include "base/bind.h"
17 #include "base/compiler_specific.h"
18 #include "base/format_macros.h"
19 #include "base/memory/ref_counted.h"
20 #include "base/metrics/field_trial.h"
21 #include "base/metrics/histogram.h"
22 #include "base/metrics/sparse_histogram.h"
23 #include "base/rand_util.h"
24 #include "base/strings/string_number_conversions.h"
25 #include "base/strings/string_piece.h"
26 #include "base/strings/string_util.h"
27 #include "base/strings/stringprintf.h"
28 #include "base/time/time.h"
29 #include "net/base/completion_callback.h"
30 #include "net/base/io_buffer.h"
31 #include "net/base/load_flags.h"
32 #include "net/base/load_timing_info.h"
33 #include "net/base/net_errors.h"
34 #include "net/base/net_log.h"
35 #include "net/base/upload_data_stream.h"
36 #include "net/cert/cert_status_flags.h"
37 #include "net/disk_cache/disk_cache.h"
38 #include "net/http/disk_based_cert_cache.h"
39 #include "net/http/http_network_session.h"
40 #include "net/http/http_request_info.h"
41 #include "net/http/http_response_headers.h"
42 #include "net/http/http_transaction.h"
43 #include "net/http/http_util.h"
44 #include "net/http/partial_data.h"
45 #include "net/ssl/ssl_cert_request_info.h"
46 #include "net/ssl/ssl_config_service.h"
49 using base::TimeDelta
;
50 using base::TimeTicks
;
54 // TODO(ricea): Move this to HttpResponseHeaders once it is standardised.
55 static const char kFreshnessHeader
[] = "Resource-Freshness";
57 // Stores data relevant to the statistics of writing and reading entire
58 // certificate chains using DiskBasedCertCache. |num_pending_ops| is the number
59 // of certificates in the chain that have pending operations in the
60 // DiskBasedCertCache. |start_time| is the time that the read and write
61 // commands began being issued to the DiskBasedCertCache.
62 // TODO(brandonsalmon): Remove this when it is no longer necessary to
64 class SharedChainData
: public base::RefCounted
<SharedChainData
> {
66 SharedChainData(int num_ops
, TimeTicks start
)
67 : num_pending_ops(num_ops
), start_time(start
) {}
73 friend class base::RefCounted
<SharedChainData
>;
75 DISALLOW_COPY_AND_ASSIGN(SharedChainData
);
78 // Used to obtain a cache entry key for an OSCertHandle.
79 // TODO(brandonsalmon): Remove this when cache keys are stored
80 // and no longer have to be recomputed to retrieve the OSCertHandle
82 std::string
GetCacheKeyForCert(net::X509Certificate::OSCertHandle cert_handle
) {
83 net::SHA1HashValue fingerprint
=
84 net::X509Certificate::CalculateFingerprint(cert_handle
);
87 base::HexEncode(fingerprint
.data
, arraysize(fingerprint
.data
));
90 // |dist_from_root| indicates the position of the read certificate in the
91 // certificate chain, 0 indicating it is the root. |is_leaf| indicates
92 // whether or not the read certificate was the leaf of the chain.
93 // |shared_chain_data| contains data shared by each certificate in
95 void OnCertReadIOComplete(
98 const scoped_refptr
<SharedChainData
>& shared_chain_data
,
99 net::X509Certificate::OSCertHandle cert_handle
) {
100 // If |num_pending_ops| is one, this was the last pending read operation
101 // for this chain of certificates. The total time used to read the chain
102 // can be calculated by subtracting the starting time from Now().
103 shared_chain_data
->num_pending_ops
--;
104 if (!shared_chain_data
->num_pending_ops
) {
105 const TimeDelta read_chain_wait
=
106 TimeTicks::Now() - shared_chain_data
->start_time
;
107 UMA_HISTOGRAM_CUSTOM_TIMES("DiskBasedCertCache.ChainReadTime",
109 base::TimeDelta::FromMilliseconds(1),
110 base::TimeDelta::FromMinutes(10),
114 bool success
= (cert_handle
!= NULL
);
116 UMA_HISTOGRAM_BOOLEAN("DiskBasedCertCache.CertIoReadSuccessLeaf", success
);
119 UMA_HISTOGRAM_CUSTOM_COUNTS(
120 "DiskBasedCertCache.CertIoReadSuccess", dist_from_root
, 0, 10, 7);
122 UMA_HISTOGRAM_CUSTOM_COUNTS(
123 "DiskBasedCertCache.CertIoReadFailure", dist_from_root
, 0, 10, 7);
126 // |dist_from_root| indicates the position of the written certificate in the
127 // certificate chain, 0 indicating it is the root. |is_leaf| indicates
128 // whether or not the written certificate was the leaf of the chain.
129 // |shared_chain_data| contains data shared by each certificate in
131 void OnCertWriteIOComplete(
134 const scoped_refptr
<SharedChainData
>& shared_chain_data
,
135 const std::string
& key
) {
136 // If |num_pending_ops| is one, this was the last pending write operation
137 // for this chain of certificates. The total time used to write the chain
138 // can be calculated by subtracting the starting time from Now().
139 shared_chain_data
->num_pending_ops
--;
140 if (!shared_chain_data
->num_pending_ops
) {
141 const TimeDelta write_chain_wait
=
142 TimeTicks::Now() - shared_chain_data
->start_time
;
143 UMA_HISTOGRAM_CUSTOM_TIMES("DiskBasedCertCache.ChainWriteTime",
145 base::TimeDelta::FromMilliseconds(1),
146 base::TimeDelta::FromMinutes(10),
150 bool success
= !key
.empty();
152 UMA_HISTOGRAM_BOOLEAN("DiskBasedCertCache.CertIoWriteSuccessLeaf", success
);
155 UMA_HISTOGRAM_CUSTOM_COUNTS(
156 "DiskBasedCertCache.CertIoWriteSuccess", dist_from_root
, 0, 10, 7);
158 UMA_HISTOGRAM_CUSTOM_COUNTS(
159 "DiskBasedCertCache.CertIoWriteFailure", dist_from_root
, 0, 10, 7);
162 // From http://tools.ietf.org/html/draft-ietf-httpbis-p6-cache-21#section-6
163 // a "non-error response" is one with a 2xx (Successful) or 3xx
164 // (Redirection) status code.
165 bool NonErrorResponse(int status_code
) {
166 int status_code_range
= status_code
/ 100;
167 return status_code_range
== 2 || status_code_range
== 3;
170 // Error codes that will be considered indicative of a page being offline/
171 // unreachable for LOAD_FROM_CACHE_IF_OFFLINE.
172 bool IsOfflineError(int error
) {
173 return (error
== net::ERR_NAME_NOT_RESOLVED
||
174 error
== net::ERR_INTERNET_DISCONNECTED
||
175 error
== net::ERR_ADDRESS_UNREACHABLE
||
176 error
== net::ERR_CONNECTION_TIMED_OUT
);
179 // Enum for UMA, indicating the status (with regard to offline mode) of
180 // a particular request.
181 enum RequestOfflineStatus
{
182 // A cache transaction hit in cache (data was present and not stale)
184 OFFLINE_STATUS_FRESH_CACHE
,
186 // A network request was required for a cache entry, and it succeeded.
187 OFFLINE_STATUS_NETWORK_SUCCEEDED
,
189 // A network request was required for a cache entry, and it failed with
190 // a non-offline error.
191 OFFLINE_STATUS_NETWORK_FAILED
,
193 // A network request was required for a cache entry, it failed with an
194 // offline error, and we could serve stale data if
195 // LOAD_FROM_CACHE_IF_OFFLINE was set.
196 OFFLINE_STATUS_DATA_AVAILABLE_OFFLINE
,
198 // A network request was required for a cache entry, it failed with
199 // an offline error, and there was no servable data in cache (even
201 OFFLINE_STATUS_DATA_UNAVAILABLE_OFFLINE
,
203 OFFLINE_STATUS_MAX_ENTRIES
206 void RecordOfflineStatus(int load_flags
, RequestOfflineStatus status
) {
207 // Restrict to main frame to keep statistics close to
208 // "would have shown them something useful if offline mode was enabled".
209 if (load_flags
& net::LOAD_MAIN_FRAME
) {
210 UMA_HISTOGRAM_ENUMERATION("HttpCache.OfflineStatus", status
,
211 OFFLINE_STATUS_MAX_ENTRIES
);
215 // TODO(rvargas): Remove once we get the data.
216 void RecordVaryHeaderHistogram(const net::HttpResponseInfo
* response
) {
223 VaryType vary
= VARY_NOT_PRESENT
;
224 if (response
->vary_data
.is_valid()) {
226 if (response
->headers
->HasHeaderValue("vary", "user-agent"))
229 UMA_HISTOGRAM_ENUMERATION("HttpCache.Vary", vary
, VARY_MAX
);
232 void RecordNoStoreHeaderHistogram(int load_flags
,
233 const net::HttpResponseInfo
* response
) {
234 if (load_flags
& net::LOAD_MAIN_FRAME
) {
235 UMA_HISTOGRAM_BOOLEAN(
236 "Net.MainFrameNoStore",
237 response
->headers
->HasHeaderValue("cache-control", "no-store"));
241 enum ExternallyConditionalizedType
{
242 EXTERNALLY_CONDITIONALIZED_CACHE_REQUIRES_VALIDATION
,
243 EXTERNALLY_CONDITIONALIZED_CACHE_USABLE
,
244 EXTERNALLY_CONDITIONALIZED_MISMATCHED_VALIDATORS
,
245 EXTERNALLY_CONDITIONALIZED_MAX
252 struct HeaderNameAndValue
{
257 // If the request includes one of these request headers, then avoid caching
258 // to avoid getting confused.
259 static const HeaderNameAndValue kPassThroughHeaders
[] = {
260 { "if-unmodified-since", NULL
}, // causes unexpected 412s
261 { "if-match", NULL
}, // causes unexpected 412s
262 { "if-range", NULL
},
266 struct ValidationHeaderInfo
{
267 const char* request_header_name
;
268 const char* related_response_header_name
;
271 static const ValidationHeaderInfo kValidationHeaders
[] = {
272 { "if-modified-since", "last-modified" },
273 { "if-none-match", "etag" },
276 // If the request includes one of these request headers, then avoid reusing
277 // our cached copy if any.
278 static const HeaderNameAndValue kForceFetchHeaders
[] = {
279 { "cache-control", "no-cache" },
280 { "pragma", "no-cache" },
284 // If the request includes one of these request headers, then force our
285 // cached copy (if any) to be revalidated before reusing it.
286 static const HeaderNameAndValue kForceValidateHeaders
[] = {
287 { "cache-control", "max-age=0" },
291 static bool HeaderMatches(const HttpRequestHeaders
& headers
,
292 const HeaderNameAndValue
* search
) {
293 for (; search
->name
; ++search
) {
294 std::string header_value
;
295 if (!headers
.GetHeader(search
->name
, &header_value
))
301 HttpUtil::ValuesIterator
v(header_value
.begin(), header_value
.end(), ',');
302 while (v
.GetNext()) {
303 if (LowerCaseEqualsASCII(v
.value_begin(), v
.value_end(), search
->value
))
310 //-----------------------------------------------------------------------------
312 HttpCache::Transaction::Transaction(
313 RequestPriority priority
,
315 : next_state_(STATE_NONE
),
318 cache_(cache
->GetWeakPtr()),
323 target_state_(STATE_NONE
),
325 invalid_range_(false),
328 range_requested_(false),
329 handling_206_(false),
330 cache_pending_(false),
331 done_reading_(false),
332 vary_mismatch_(false),
333 couldnt_conditionalize_request_(false),
334 bypass_lock_for_test_(false),
337 effective_load_flags_(0),
339 transaction_pattern_(PATTERN_UNDEFINED
),
340 total_received_bytes_(0),
341 websocket_handshake_stream_base_create_helper_(NULL
),
342 weak_factory_(this) {
343 COMPILE_ASSERT(HttpCache::Transaction::kNumValidationHeaders
==
344 arraysize(kValidationHeaders
),
345 Invalid_number_of_validation_headers
);
347 io_callback_
= base::Bind(&Transaction::OnIOComplete
,
348 weak_factory_
.GetWeakPtr());
351 HttpCache::Transaction::~Transaction() {
352 // We may have to issue another IO, but we should never invoke the callback_
358 bool cancel_request
= reading_
&& response_
.headers
.get();
359 if (cancel_request
) {
361 entry_
->disk_entry
->CancelSparseIO();
363 cancel_request
&= (response_
.headers
->response_code() == 200);
367 cache_
->DoneWithEntry(entry_
, this, cancel_request
);
368 } else if (cache_pending_
) {
369 cache_
->RemovePendingTransaction(this);
374 int HttpCache::Transaction::WriteMetadata(IOBuffer
* buf
, int buf_len
,
375 const CompletionCallback
& callback
) {
377 DCHECK_GT(buf_len
, 0);
378 DCHECK(!callback
.is_null());
379 if (!cache_
.get() || !entry_
)
380 return ERR_UNEXPECTED
;
382 // We don't need to track this operation for anything.
383 // It could be possible to check if there is something already written and
384 // avoid writing again (it should be the same, right?), but let's allow the
385 // caller to "update" the contents with something new.
386 return entry_
->disk_entry
->WriteData(kMetadataIndex
, 0, buf
, buf_len
,
390 bool HttpCache::Transaction::AddTruncatedFlag() {
391 DCHECK(mode_
& WRITE
|| mode_
== NONE
);
393 // Don't set the flag for sparse entries.
394 if (partial_
.get() && !truncated_
)
397 if (!CanResume(true))
400 // We may have received the whole resource already.
405 target_state_
= STATE_NONE
;
406 next_state_
= STATE_CACHE_WRITE_TRUNCATED_RESPONSE
;
411 LoadState
HttpCache::Transaction::GetWriterLoadState() const {
412 if (network_trans_
.get())
413 return network_trans_
->GetLoadState();
414 if (entry_
|| !request_
)
415 return LOAD_STATE_IDLE
;
416 return LOAD_STATE_WAITING_FOR_CACHE
;
419 const BoundNetLog
& HttpCache::Transaction::net_log() const {
423 int HttpCache::Transaction::Start(const HttpRequestInfo
* request
,
424 const CompletionCallback
& callback
,
425 const BoundNetLog
& net_log
) {
427 DCHECK(!callback
.is_null());
429 // Ensure that we only have one asynchronous call at a time.
430 DCHECK(callback_
.is_null());
432 DCHECK(!network_trans_
.get());
436 return ERR_UNEXPECTED
;
438 SetRequest(net_log
, request
);
440 // We have to wait until the backend is initialized so we start the SM.
441 next_state_
= STATE_GET_BACKEND
;
444 // Setting this here allows us to check for the existence of a callback_ to
445 // determine if we are still inside Start.
446 if (rv
== ERR_IO_PENDING
)
447 callback_
= callback
;
452 int HttpCache::Transaction::RestartIgnoringLastError(
453 const CompletionCallback
& callback
) {
454 DCHECK(!callback
.is_null());
456 // Ensure that we only have one asynchronous call at a time.
457 DCHECK(callback_
.is_null());
460 return ERR_UNEXPECTED
;
462 int rv
= RestartNetworkRequest();
464 if (rv
== ERR_IO_PENDING
)
465 callback_
= callback
;
470 int HttpCache::Transaction::RestartWithCertificate(
471 X509Certificate
* client_cert
,
472 const CompletionCallback
& callback
) {
473 DCHECK(!callback
.is_null());
475 // Ensure that we only have one asynchronous call at a time.
476 DCHECK(callback_
.is_null());
479 return ERR_UNEXPECTED
;
481 int rv
= RestartNetworkRequestWithCertificate(client_cert
);
483 if (rv
== ERR_IO_PENDING
)
484 callback_
= callback
;
489 int HttpCache::Transaction::RestartWithAuth(
490 const AuthCredentials
& credentials
,
491 const CompletionCallback
& callback
) {
492 DCHECK(auth_response_
.headers
.get());
493 DCHECK(!callback
.is_null());
495 // Ensure that we only have one asynchronous call at a time.
496 DCHECK(callback_
.is_null());
499 return ERR_UNEXPECTED
;
501 // Clear the intermediate response since we are going to start over.
502 auth_response_
= HttpResponseInfo();
504 int rv
= RestartNetworkRequestWithAuth(credentials
);
506 if (rv
== ERR_IO_PENDING
)
507 callback_
= callback
;
512 bool HttpCache::Transaction::IsReadyToRestartForAuth() {
513 if (!network_trans_
.get())
515 return network_trans_
->IsReadyToRestartForAuth();
518 int HttpCache::Transaction::Read(IOBuffer
* buf
, int buf_len
,
519 const CompletionCallback
& callback
) {
521 DCHECK_GT(buf_len
, 0);
522 DCHECK(!callback
.is_null());
524 DCHECK(callback_
.is_null());
527 return ERR_UNEXPECTED
;
529 // If we have an intermediate auth response at this point, then it means the
530 // user wishes to read the network response (the error page). If there is a
531 // previous response in the cache then we should leave it intact.
532 if (auth_response_
.headers
.get() && mode_
!= NONE
) {
533 UpdateTransactionPattern(PATTERN_NOT_COVERED
);
534 DCHECK(mode_
& WRITE
);
535 DoneWritingToEntry(mode_
== READ_WRITE
);
544 DCHECK(partial_
.get());
545 if (!network_trans_
.get()) {
546 // We are just reading from the cache, but we may be writing later.
547 rv
= ReadFromEntry(buf
, buf_len
);
552 DCHECK(network_trans_
.get());
553 rv
= ReadFromNetwork(buf
, buf_len
);
556 rv
= ReadFromEntry(buf
, buf_len
);
563 if (rv
== ERR_IO_PENDING
) {
564 DCHECK(callback_
.is_null());
565 callback_
= callback
;
570 void HttpCache::Transaction::StopCaching() {
571 // We really don't know where we are now. Hopefully there is no operation in
572 // progress, but nothing really prevents this method to be called after we
573 // returned ERR_IO_PENDING. We cannot attempt to truncate the entry at this
574 // point because we need the state machine for that (and even if we are really
575 // free, that would be an asynchronous operation). In other words, keep the
576 // entry how it is (it will be marked as truncated at destruction), and let
577 // the next piece of code that executes know that we are now reading directly
579 // TODO(mmenke): This doesn't release the lock on the cache entry, so a
580 // future request for the resource will be blocked on this one.
582 if (cache_
.get() && entry_
&& (mode_
& WRITE
) && network_trans_
.get() &&
583 !is_sparse_
&& !range_requested_
) {
588 bool HttpCache::Transaction::GetFullRequestHeaders(
589 HttpRequestHeaders
* headers
) const {
591 return network_trans_
->GetFullRequestHeaders(headers
);
593 // TODO(ttuttle): Read headers from cache.
597 int64
HttpCache::Transaction::GetTotalReceivedBytes() const {
598 int64 total_received_bytes
= total_received_bytes_
;
600 total_received_bytes
+= network_trans_
->GetTotalReceivedBytes();
601 return total_received_bytes
;
604 void HttpCache::Transaction::DoneReading() {
605 if (cache_
.get() && entry_
) {
606 DCHECK_NE(mode_
, UPDATE
);
608 DoneWritingToEntry(true);
609 } else if (mode_
& READ
) {
610 // It is necessary to check mode_ & READ because it is possible
611 // for mode_ to be NONE and entry_ non-NULL with a write entry
612 // if StopCaching was called.
613 cache_
->DoneReadingFromEntry(entry_
, this);
619 const HttpResponseInfo
* HttpCache::Transaction::GetResponseInfo() const {
620 // Null headers means we encountered an error or haven't a response yet
621 if (auth_response_
.headers
.get())
622 return &auth_response_
;
623 return (response_
.headers
.get() || response_
.ssl_info
.cert
.get() ||
624 response_
.cert_request_info
.get())
629 LoadState
HttpCache::Transaction::GetLoadState() const {
630 LoadState state
= GetWriterLoadState();
631 if (state
!= LOAD_STATE_WAITING_FOR_CACHE
)
635 return cache_
->GetLoadStateForPendingTransaction(this);
637 return LOAD_STATE_IDLE
;
640 UploadProgress
HttpCache::Transaction::GetUploadProgress() const {
641 if (network_trans_
.get())
642 return network_trans_
->GetUploadProgress();
643 return final_upload_progress_
;
646 void HttpCache::Transaction::SetQuicServerInfo(
647 QuicServerInfo
* quic_server_info
) {}
649 bool HttpCache::Transaction::GetLoadTimingInfo(
650 LoadTimingInfo
* load_timing_info
) const {
652 return network_trans_
->GetLoadTimingInfo(load_timing_info
);
654 if (old_network_trans_load_timing_
) {
655 *load_timing_info
= *old_network_trans_load_timing_
;
659 if (first_cache_access_since_
.is_null())
662 // If the cache entry was opened, return that time.
663 load_timing_info
->send_start
= first_cache_access_since_
;
664 // This time doesn't make much sense when reading from the cache, so just use
665 // the same time as send_start.
666 load_timing_info
->send_end
= first_cache_access_since_
;
670 void HttpCache::Transaction::SetPriority(RequestPriority priority
) {
671 priority_
= priority
;
673 network_trans_
->SetPriority(priority_
);
676 void HttpCache::Transaction::SetWebSocketHandshakeStreamCreateHelper(
677 WebSocketHandshakeStreamBase::CreateHelper
* create_helper
) {
678 websocket_handshake_stream_base_create_helper_
= create_helper
;
680 network_trans_
->SetWebSocketHandshakeStreamCreateHelper(create_helper
);
683 void HttpCache::Transaction::SetBeforeNetworkStartCallback(
684 const BeforeNetworkStartCallback
& callback
) {
685 DCHECK(!network_trans_
);
686 before_network_start_callback_
= callback
;
689 void HttpCache::Transaction::SetBeforeProxyHeadersSentCallback(
690 const BeforeProxyHeadersSentCallback
& callback
) {
691 DCHECK(!network_trans_
);
692 before_proxy_headers_sent_callback_
= callback
;
695 int HttpCache::Transaction::ResumeNetworkStart() {
697 return network_trans_
->ResumeNetworkStart();
698 return ERR_UNEXPECTED
;
701 //-----------------------------------------------------------------------------
703 void HttpCache::Transaction::DoCallback(int rv
) {
704 DCHECK(rv
!= ERR_IO_PENDING
);
705 DCHECK(!callback_
.is_null());
707 read_buf_
= NULL
; // Release the buffer before invoking the callback.
709 // Since Run may result in Read being called, clear callback_ up front.
710 CompletionCallback c
= callback_
;
715 int HttpCache::Transaction::HandleResult(int rv
) {
716 DCHECK(rv
!= ERR_IO_PENDING
);
717 if (!callback_
.is_null())
723 // A few common patterns: (Foo* means Foo -> FooComplete)
725 // 1. Not-cached entry:
727 // GetBackend* -> InitEntry -> OpenEntry* -> CreateEntry* -> AddToEntry* ->
728 // SendRequest* -> SuccessfulSendRequest -> OverwriteCachedResponse ->
729 // CacheWriteResponse* -> TruncateCachedData* -> TruncateCachedMetadata* ->
730 // PartialHeadersReceived
733 // NetworkRead* -> CacheWriteData*
735 // 2. Cached entry, no validation:
737 // GetBackend* -> InitEntry -> OpenEntry* -> AddToEntry* -> CacheReadResponse*
738 // -> BeginPartialCacheValidation() -> BeginCacheValidation() ->
739 // SetupEntryForRead()
744 // 3. Cached entry, validation (304):
746 // GetBackend* -> InitEntry -> OpenEntry* -> AddToEntry* -> CacheReadResponse*
747 // -> BeginPartialCacheValidation() -> BeginCacheValidation() ->
748 // SendRequest* -> SuccessfulSendRequest -> UpdateCachedResponse ->
749 // CacheWriteResponse* -> UpdateCachedResponseComplete ->
750 // OverwriteCachedResponse -> PartialHeadersReceived
755 // 4. Cached entry, validation and replace (200):
757 // GetBackend* -> InitEntry -> OpenEntry* -> AddToEntry* -> CacheReadResponse*
758 // -> BeginPartialCacheValidation() -> BeginCacheValidation() ->
759 // SendRequest* -> SuccessfulSendRequest -> OverwriteCachedResponse ->
760 // CacheWriteResponse* -> DoTruncateCachedData* -> TruncateCachedMetadata* ->
761 // PartialHeadersReceived
764 // NetworkRead* -> CacheWriteData*
766 // 5. Sparse entry, partially cached, byte range request:
768 // GetBackend* -> InitEntry -> OpenEntry* -> AddToEntry* -> CacheReadResponse*
769 // -> BeginPartialCacheValidation() -> CacheQueryData* ->
770 // ValidateEntryHeadersAndContinue() -> StartPartialCacheValidation ->
771 // CompletePartialCacheValidation -> BeginCacheValidation() -> SendRequest* ->
772 // SuccessfulSendRequest -> UpdateCachedResponse -> CacheWriteResponse* ->
773 // UpdateCachedResponseComplete -> OverwriteCachedResponse ->
774 // PartialHeadersReceived
777 // NetworkRead* -> CacheWriteData*
780 // NetworkRead* -> CacheWriteData* -> StartPartialCacheValidation ->
781 // CompletePartialCacheValidation -> CacheReadData* ->
784 // CacheReadData* -> StartPartialCacheValidation ->
785 // CompletePartialCacheValidation -> BeginCacheValidation() -> SendRequest* ->
786 // SuccessfulSendRequest -> UpdateCachedResponse* -> OverwriteCachedResponse
787 // -> PartialHeadersReceived -> NetworkRead* -> CacheWriteData*
789 // 6. HEAD. Not-cached entry:
790 // Pass through. Don't save a HEAD by itself.
792 // GetBackend* -> InitEntry -> OpenEntry* -> SendRequest*
794 // 7. HEAD. Cached entry, no validation:
796 // The same flow as for a GET request (example #2)
799 // CacheReadData (returns 0)
801 // 8. HEAD. Cached entry, validation (304):
802 // The request updates the stored headers.
803 // Start(): Same as for a GET request (example #3)
806 // CacheReadData (returns 0)
808 // 9. HEAD. Cached entry, validation and replace (200):
809 // Pass through. The request dooms the old entry, as a HEAD won't be stored by
812 // GetBackend* -> InitEntry -> OpenEntry* -> AddToEntry* -> CacheReadResponse*
813 // -> BeginPartialCacheValidation() -> BeginCacheValidation() ->
814 // SendRequest* -> SuccessfulSendRequest -> OverwriteCachedResponse
816 // 10. HEAD. Sparse entry, partially cached:
817 // Serve the request from the cache, as long as it doesn't require
818 // revalidation. Ignore missing ranges when deciding to revalidate. If the
819 // entry requires revalidation, ignore the whole request and go to full pass
820 // through (the result of the HEAD request will NOT update the entry).
822 // Start(): Basically the same as example 7, as we never create a partial_
823 // object for this request.
825 int HttpCache::Transaction::DoLoop(int result
) {
826 DCHECK(next_state_
!= STATE_NONE
);
830 State state
= next_state_
;
831 next_state_
= STATE_NONE
;
833 case STATE_GET_BACKEND
:
837 case STATE_GET_BACKEND_COMPLETE
:
838 rv
= DoGetBackendComplete(rv
);
840 case STATE_SEND_REQUEST
:
842 rv
= DoSendRequest();
844 case STATE_SEND_REQUEST_COMPLETE
:
845 rv
= DoSendRequestComplete(rv
);
847 case STATE_SUCCESSFUL_SEND_REQUEST
:
849 rv
= DoSuccessfulSendRequest();
851 case STATE_NETWORK_READ
:
853 rv
= DoNetworkRead();
855 case STATE_NETWORK_READ_COMPLETE
:
856 rv
= DoNetworkReadComplete(rv
);
858 case STATE_INIT_ENTRY
:
862 case STATE_OPEN_ENTRY
:
866 case STATE_OPEN_ENTRY_COMPLETE
:
867 rv
= DoOpenEntryComplete(rv
);
869 case STATE_CREATE_ENTRY
:
871 rv
= DoCreateEntry();
873 case STATE_CREATE_ENTRY_COMPLETE
:
874 rv
= DoCreateEntryComplete(rv
);
876 case STATE_DOOM_ENTRY
:
880 case STATE_DOOM_ENTRY_COMPLETE
:
881 rv
= DoDoomEntryComplete(rv
);
883 case STATE_ADD_TO_ENTRY
:
887 case STATE_ADD_TO_ENTRY_COMPLETE
:
888 rv
= DoAddToEntryComplete(rv
);
890 case STATE_START_PARTIAL_CACHE_VALIDATION
:
892 rv
= DoStartPartialCacheValidation();
894 case STATE_COMPLETE_PARTIAL_CACHE_VALIDATION
:
895 rv
= DoCompletePartialCacheValidation(rv
);
897 case STATE_UPDATE_CACHED_RESPONSE
:
899 rv
= DoUpdateCachedResponse();
901 case STATE_UPDATE_CACHED_RESPONSE_COMPLETE
:
902 rv
= DoUpdateCachedResponseComplete(rv
);
904 case STATE_OVERWRITE_CACHED_RESPONSE
:
906 rv
= DoOverwriteCachedResponse();
908 case STATE_TRUNCATE_CACHED_DATA
:
910 rv
= DoTruncateCachedData();
912 case STATE_TRUNCATE_CACHED_DATA_COMPLETE
:
913 rv
= DoTruncateCachedDataComplete(rv
);
915 case STATE_TRUNCATE_CACHED_METADATA
:
917 rv
= DoTruncateCachedMetadata();
919 case STATE_TRUNCATE_CACHED_METADATA_COMPLETE
:
920 rv
= DoTruncateCachedMetadataComplete(rv
);
922 case STATE_PARTIAL_HEADERS_RECEIVED
:
924 rv
= DoPartialHeadersReceived();
926 case STATE_CACHE_READ_RESPONSE
:
928 rv
= DoCacheReadResponse();
930 case STATE_CACHE_READ_RESPONSE_COMPLETE
:
931 rv
= DoCacheReadResponseComplete(rv
);
933 case STATE_CACHE_WRITE_RESPONSE
:
935 rv
= DoCacheWriteResponse();
937 case STATE_CACHE_WRITE_TRUNCATED_RESPONSE
:
939 rv
= DoCacheWriteTruncatedResponse();
941 case STATE_CACHE_WRITE_RESPONSE_COMPLETE
:
942 rv
= DoCacheWriteResponseComplete(rv
);
944 case STATE_CACHE_READ_METADATA
:
946 rv
= DoCacheReadMetadata();
948 case STATE_CACHE_READ_METADATA_COMPLETE
:
949 rv
= DoCacheReadMetadataComplete(rv
);
951 case STATE_CACHE_QUERY_DATA
:
953 rv
= DoCacheQueryData();
955 case STATE_CACHE_QUERY_DATA_COMPLETE
:
956 rv
= DoCacheQueryDataComplete(rv
);
958 case STATE_CACHE_READ_DATA
:
960 rv
= DoCacheReadData();
962 case STATE_CACHE_READ_DATA_COMPLETE
:
963 rv
= DoCacheReadDataComplete(rv
);
965 case STATE_CACHE_WRITE_DATA
:
966 rv
= DoCacheWriteData(rv
);
968 case STATE_CACHE_WRITE_DATA_COMPLETE
:
969 rv
= DoCacheWriteDataComplete(rv
);
972 NOTREACHED() << "bad state";
976 } while (rv
!= ERR_IO_PENDING
&& next_state_
!= STATE_NONE
);
978 if (rv
!= ERR_IO_PENDING
)
984 int HttpCache::Transaction::DoGetBackend() {
985 cache_pending_
= true;
986 next_state_
= STATE_GET_BACKEND_COMPLETE
;
987 net_log_
.BeginEvent(NetLog::TYPE_HTTP_CACHE_GET_BACKEND
);
988 return cache_
->GetBackendForTransaction(this);
991 int HttpCache::Transaction::DoGetBackendComplete(int result
) {
992 DCHECK(result
== OK
|| result
== ERR_FAILED
);
993 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_HTTP_CACHE_GET_BACKEND
,
995 cache_pending_
= false;
997 if (!ShouldPassThrough()) {
998 cache_key_
= cache_
->GenerateCacheKey(request_
);
1000 // Requested cache access mode.
1001 if (effective_load_flags_
& LOAD_ONLY_FROM_CACHE
) {
1003 } else if (effective_load_flags_
& LOAD_BYPASS_CACHE
) {
1009 // Downgrade to UPDATE if the request has been externally conditionalized.
1010 if (external_validation_
.initialized
) {
1011 if (mode_
& WRITE
) {
1012 // Strip off the READ_DATA bit (and maybe add back a READ_META bit
1013 // in case READ was off).
1021 // Use PUT and DELETE only to invalidate existing stored entries.
1022 if ((request_
->method
== "PUT" || request_
->method
== "DELETE") &&
1023 mode_
!= READ_WRITE
&& mode_
!= WRITE
) {
1027 // Note that if mode_ == UPDATE (which is tied to external_validation_), the
1028 // transaction behaves the same for GET and HEAD requests at this point: if it
1029 // was not modified, the entry is updated and a response is not returned from
1030 // the cache. If we receive 200, it doesn't matter if there was a validation
1032 if (request_
->method
== "HEAD" && mode_
== WRITE
)
1035 // If must use cache, then we must fail. This can happen for back/forward
1036 // navigations to a page generated via a form post.
1037 if (!(mode_
& READ
) && effective_load_flags_
& LOAD_ONLY_FROM_CACHE
)
1038 return ERR_CACHE_MISS
;
1040 if (mode_
== NONE
) {
1041 if (partial_
.get()) {
1042 partial_
->RestoreHeaders(&custom_request_
->extra_headers
);
1045 next_state_
= STATE_SEND_REQUEST
;
1047 next_state_
= STATE_INIT_ENTRY
;
1050 // This is only set if we have something to do with the response.
1051 range_requested_
= (partial_
.get() != NULL
);
1056 int HttpCache::Transaction::DoSendRequest() {
1057 DCHECK(mode_
& WRITE
|| mode_
== NONE
);
1058 DCHECK(!network_trans_
.get());
1060 send_request_since_
= TimeTicks::Now();
1062 // Create a network transaction.
1063 int rv
= cache_
->network_layer_
->CreateTransaction(priority_
,
1067 network_trans_
->SetBeforeNetworkStartCallback(before_network_start_callback_
);
1068 network_trans_
->SetBeforeProxyHeadersSentCallback(
1069 before_proxy_headers_sent_callback_
);
1071 // Old load timing information, if any, is now obsolete.
1072 old_network_trans_load_timing_
.reset();
1074 if (websocket_handshake_stream_base_create_helper_
)
1075 network_trans_
->SetWebSocketHandshakeStreamCreateHelper(
1076 websocket_handshake_stream_base_create_helper_
);
1078 next_state_
= STATE_SEND_REQUEST_COMPLETE
;
1079 rv
= network_trans_
->Start(request_
, io_callback_
, net_log_
);
1083 int HttpCache::Transaction::DoSendRequestComplete(int result
) {
1085 return ERR_UNEXPECTED
;
1087 // If requested, and we have a readable cache entry, and we have
1088 // an error indicating that we're offline as opposed to in contact
1089 // with a bad server, read from cache anyway.
1090 if (IsOfflineError(result
)) {
1091 if (mode_
== READ_WRITE
&& entry_
&& !partial_
) {
1092 RecordOfflineStatus(effective_load_flags_
,
1093 OFFLINE_STATUS_DATA_AVAILABLE_OFFLINE
);
1094 if (effective_load_flags_
& LOAD_FROM_CACHE_IF_OFFLINE
) {
1095 UpdateTransactionPattern(PATTERN_NOT_COVERED
);
1096 response_
.server_data_unavailable
= true;
1097 return SetupEntryForRead();
1100 RecordOfflineStatus(effective_load_flags_
,
1101 OFFLINE_STATUS_DATA_UNAVAILABLE_OFFLINE
);
1104 RecordOfflineStatus(effective_load_flags_
,
1105 (result
== OK
? OFFLINE_STATUS_NETWORK_SUCCEEDED
:
1106 OFFLINE_STATUS_NETWORK_FAILED
));
1109 // If we tried to conditionalize the request and failed, we know
1110 // we won't be reading from the cache after this point.
1111 if (couldnt_conditionalize_request_
)
1115 next_state_
= STATE_SUCCESSFUL_SEND_REQUEST
;
1119 // Do not record requests that have network errors or restarts.
1120 UpdateTransactionPattern(PATTERN_NOT_COVERED
);
1121 if (IsCertificateError(result
)) {
1122 const HttpResponseInfo
* response
= network_trans_
->GetResponseInfo();
1123 // If we get a certificate error, then there is a certificate in ssl_info,
1124 // so GetResponseInfo() should never return NULL here.
1126 response_
.ssl_info
= response
->ssl_info
;
1127 } else if (result
== ERR_SSL_CLIENT_AUTH_CERT_NEEDED
) {
1128 const HttpResponseInfo
* response
= network_trans_
->GetResponseInfo();
1130 response_
.cert_request_info
= response
->cert_request_info
;
1131 } else if (response_
.was_cached
) {
1132 DoneWritingToEntry(true);
1137 // We received the response headers and there is no error.
1138 int HttpCache::Transaction::DoSuccessfulSendRequest() {
1139 DCHECK(!new_response_
);
1140 const HttpResponseInfo
* new_response
= network_trans_
->GetResponseInfo();
1141 bool authentication_failure
= false;
1143 if (new_response
->headers
->response_code() == 401 ||
1144 new_response
->headers
->response_code() == 407) {
1145 auth_response_
= *new_response
;
1149 // We initiated a second request the caller doesn't know about. We should be
1150 // able to authenticate this request because we should have authenticated
1151 // this URL moments ago.
1152 if (IsReadyToRestartForAuth()) {
1153 DCHECK(!response_
.auth_challenge
.get());
1154 next_state_
= STATE_SEND_REQUEST_COMPLETE
;
1155 // In theory we should check to see if there are new cookies, but there
1156 // is no way to do that from here.
1157 return network_trans_
->RestartWithAuth(AuthCredentials(), io_callback_
);
1160 // We have to perform cleanup at this point so that at least the next
1161 // request can succeed.
1162 authentication_failure
= true;
1164 DoomPartialEntry(false);
1169 new_response_
= new_response
;
1170 if (authentication_failure
||
1171 (!ValidatePartialResponse() && !auth_response_
.headers
.get())) {
1172 // Something went wrong with this request and we have to restart it.
1173 // If we have an authentication response, we are exposed to weird things
1174 // hapenning if the user cancels the authentication before we receive
1175 // the new response.
1176 UpdateTransactionPattern(PATTERN_NOT_COVERED
);
1177 response_
= HttpResponseInfo();
1178 ResetNetworkTransaction();
1179 new_response_
= NULL
;
1180 next_state_
= STATE_SEND_REQUEST
;
1184 if (handling_206_
&& mode_
== READ_WRITE
&& !truncated_
&& !is_sparse_
) {
1185 // We have stored the full entry, but it changed and the server is
1186 // sending a range. We have to delete the old entry.
1187 UpdateTransactionPattern(PATTERN_NOT_COVERED
);
1188 DoneWritingToEntry(false);
1191 if (mode_
== WRITE
&&
1192 transaction_pattern_
!= PATTERN_ENTRY_CANT_CONDITIONALIZE
) {
1193 UpdateTransactionPattern(PATTERN_ENTRY_NOT_CACHED
);
1196 if (mode_
== WRITE
&&
1197 (request_
->method
== "PUT" || request_
->method
== "DELETE")) {
1198 if (NonErrorResponse(new_response
->headers
->response_code())) {
1199 int ret
= cache_
->DoomEntry(cache_key_
, NULL
);
1202 cache_
->DoneWritingToEntry(entry_
, true);
1207 if (request_
->method
== "POST" &&
1208 NonErrorResponse(new_response
->headers
->response_code())) {
1209 cache_
->DoomMainEntryForUrl(request_
->url
);
1212 RecordVaryHeaderHistogram(new_response
);
1213 RecordNoStoreHeaderHistogram(request_
->load_flags
, new_response
);
1215 if (new_response_
->headers
->response_code() == 416 &&
1216 (request_
->method
== "GET" || request_
->method
== "POST")) {
1217 // If there is an active entry it may be destroyed with this transaction.
1218 response_
= *new_response_
;
1222 // Are we expecting a response to a conditional query?
1223 if (mode_
== READ_WRITE
|| mode_
== UPDATE
) {
1224 if (new_response
->headers
->response_code() == 304 || handling_206_
) {
1225 UpdateTransactionPattern(PATTERN_ENTRY_VALIDATED
);
1226 next_state_
= STATE_UPDATE_CACHED_RESPONSE
;
1229 UpdateTransactionPattern(PATTERN_ENTRY_UPDATED
);
1233 next_state_
= STATE_OVERWRITE_CACHED_RESPONSE
;
1237 int HttpCache::Transaction::DoNetworkRead() {
1238 next_state_
= STATE_NETWORK_READ_COMPLETE
;
1239 return network_trans_
->Read(read_buf_
.get(), io_buf_len_
, io_callback_
);
1242 int HttpCache::Transaction::DoNetworkReadComplete(int result
) {
1243 DCHECK(mode_
& WRITE
|| mode_
== NONE
);
1246 return ERR_UNEXPECTED
;
1248 // If there is an error or we aren't saving the data, we are done; just wait
1249 // until the destructor runs to see if we can keep the data.
1250 if (mode_
== NONE
|| result
< 0)
1253 next_state_
= STATE_CACHE_WRITE_DATA
;
1257 int HttpCache::Transaction::DoInitEntry() {
1258 DCHECK(!new_entry_
);
1261 return ERR_UNEXPECTED
;
1263 if (mode_
== WRITE
) {
1264 next_state_
= STATE_DOOM_ENTRY
;
1268 next_state_
= STATE_OPEN_ENTRY
;
1272 int HttpCache::Transaction::DoOpenEntry() {
1273 DCHECK(!new_entry_
);
1274 next_state_
= STATE_OPEN_ENTRY_COMPLETE
;
1275 cache_pending_
= true;
1276 net_log_
.BeginEvent(NetLog::TYPE_HTTP_CACHE_OPEN_ENTRY
);
1277 first_cache_access_since_
= TimeTicks::Now();
1278 return cache_
->OpenEntry(cache_key_
, &new_entry_
, this);
1281 int HttpCache::Transaction::DoOpenEntryComplete(int result
) {
1282 // It is important that we go to STATE_ADD_TO_ENTRY whenever the result is
1283 // OK, otherwise the cache will end up with an active entry without any
1284 // transaction attached.
1285 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_HTTP_CACHE_OPEN_ENTRY
, result
);
1286 cache_pending_
= false;
1288 next_state_
= STATE_ADD_TO_ENTRY
;
1292 if (result
== ERR_CACHE_RACE
) {
1293 next_state_
= STATE_INIT_ENTRY
;
1297 if (request_
->method
== "PUT" || request_
->method
== "DELETE" ||
1298 (request_
->method
== "HEAD" && mode_
== READ_WRITE
)) {
1299 DCHECK(mode_
== READ_WRITE
|| mode_
== WRITE
|| request_
->method
== "HEAD");
1301 next_state_
= STATE_SEND_REQUEST
;
1305 if (mode_
== READ_WRITE
) {
1307 next_state_
= STATE_CREATE_ENTRY
;
1310 if (mode_
== UPDATE
) {
1311 // There is no cache entry to update; proceed without caching.
1313 next_state_
= STATE_SEND_REQUEST
;
1316 if (cache_
->mode() == PLAYBACK
)
1317 DVLOG(1) << "Playback Cache Miss: " << request_
->url
;
1319 // The entry does not exist, and we are not permitted to create a new entry,
1321 return ERR_CACHE_MISS
;
1324 int HttpCache::Transaction::DoCreateEntry() {
1325 DCHECK(!new_entry_
);
1326 next_state_
= STATE_CREATE_ENTRY_COMPLETE
;
1327 cache_pending_
= true;
1328 net_log_
.BeginEvent(NetLog::TYPE_HTTP_CACHE_CREATE_ENTRY
);
1329 return cache_
->CreateEntry(cache_key_
, &new_entry_
, this);
1332 int HttpCache::Transaction::DoCreateEntryComplete(int result
) {
1333 // It is important that we go to STATE_ADD_TO_ENTRY whenever the result is
1334 // OK, otherwise the cache will end up with an active entry without any
1335 // transaction attached.
1336 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_HTTP_CACHE_CREATE_ENTRY
,
1338 cache_pending_
= false;
1339 next_state_
= STATE_ADD_TO_ENTRY
;
1341 if (result
== ERR_CACHE_RACE
) {
1342 next_state_
= STATE_INIT_ENTRY
;
1347 UMA_HISTOGRAM_BOOLEAN("HttpCache.OpenToCreateRace", false);
1349 UMA_HISTOGRAM_BOOLEAN("HttpCache.OpenToCreateRace", true);
1350 // We have a race here: Maybe we failed to open the entry and decided to
1351 // create one, but by the time we called create, another transaction already
1352 // created the entry. If we want to eliminate this issue, we need an atomic
1353 // OpenOrCreate() method exposed by the disk cache.
1354 DLOG(WARNING
) << "Unable to create cache entry";
1357 partial_
->RestoreHeaders(&custom_request_
->extra_headers
);
1358 next_state_
= STATE_SEND_REQUEST
;
1363 int HttpCache::Transaction::DoDoomEntry() {
1364 next_state_
= STATE_DOOM_ENTRY_COMPLETE
;
1365 cache_pending_
= true;
1366 if (first_cache_access_since_
.is_null())
1367 first_cache_access_since_
= TimeTicks::Now();
1368 net_log_
.BeginEvent(NetLog::TYPE_HTTP_CACHE_DOOM_ENTRY
);
1369 return cache_
->DoomEntry(cache_key_
, this);
1372 int HttpCache::Transaction::DoDoomEntryComplete(int result
) {
1373 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_HTTP_CACHE_DOOM_ENTRY
, result
);
1374 next_state_
= STATE_CREATE_ENTRY
;
1375 cache_pending_
= false;
1376 if (result
== ERR_CACHE_RACE
)
1377 next_state_
= STATE_INIT_ENTRY
;
1381 int HttpCache::Transaction::DoAddToEntry() {
1383 cache_pending_
= true;
1384 next_state_
= STATE_ADD_TO_ENTRY_COMPLETE
;
1385 net_log_
.BeginEvent(NetLog::TYPE_HTTP_CACHE_ADD_TO_ENTRY
);
1386 DCHECK(entry_lock_waiting_since_
.is_null());
1387 entry_lock_waiting_since_
= TimeTicks::Now();
1388 int rv
= cache_
->AddTransactionToEntry(new_entry_
, this);
1389 if (rv
== ERR_IO_PENDING
) {
1390 if (bypass_lock_for_test_
) {
1391 OnAddToEntryTimeout(entry_lock_waiting_since_
);
1393 int timeout_secs
= 20;
1394 if (partial_
&& new_entry_
->writer
&&
1395 new_entry_
->writer
->range_requested_
) {
1396 // Immediately timeout and bypass the cache if we're a range request and
1397 // we're blocked by the reader/writer lock. Doing so eliminates a long
1398 // running issue, http://crbug.com/31014, where two of the same media
1399 // resources could not be played back simultaneously due to one locking
1400 // the cache entry until the entire video was downloaded.
1402 // Bypassing the cache is not ideal, as we are now ignoring the cache
1403 // entirely for all range requests to a resource beyond the first. This
1404 // is however a much more succinct solution than the alternatives, which
1405 // would require somewhat significant changes to the http caching logic.
1408 base::MessageLoop::current()->PostDelayedTask(
1410 base::Bind(&HttpCache::Transaction::OnAddToEntryTimeout
,
1411 weak_factory_
.GetWeakPtr(), entry_lock_waiting_since_
),
1412 TimeDelta::FromSeconds(timeout_secs
));
1418 int HttpCache::Transaction::DoAddToEntryComplete(int result
) {
1419 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_HTTP_CACHE_ADD_TO_ENTRY
,
1421 const TimeDelta entry_lock_wait
=
1422 TimeTicks::Now() - entry_lock_waiting_since_
;
1423 UMA_HISTOGRAM_TIMES("HttpCache.EntryLockWait", entry_lock_wait
);
1425 entry_lock_waiting_since_
= TimeTicks();
1427 cache_pending_
= false;
1430 entry_
= new_entry_
;
1432 // If there is a failure, the cache should have taken care of new_entry_.
1435 if (result
== ERR_CACHE_RACE
) {
1436 next_state_
= STATE_INIT_ENTRY
;
1440 if (result
== ERR_CACHE_LOCK_TIMEOUT
) {
1441 // The cache is busy, bypass it for this transaction.
1443 next_state_
= STATE_SEND_REQUEST
;
1445 partial_
->RestoreHeaders(&custom_request_
->extra_headers
);
1456 if (mode_
== WRITE
) {
1458 partial_
->RestoreHeaders(&custom_request_
->extra_headers
);
1459 next_state_
= STATE_SEND_REQUEST
;
1461 // We have to read the headers from the cached entry.
1462 DCHECK(mode_
& READ_META
);
1463 next_state_
= STATE_CACHE_READ_RESPONSE
;
1468 // We may end up here multiple times for a given request.
1469 int HttpCache::Transaction::DoStartPartialCacheValidation() {
1473 next_state_
= STATE_COMPLETE_PARTIAL_CACHE_VALIDATION
;
1474 return partial_
->ShouldValidateCache(entry_
->disk_entry
, io_callback_
);
1477 int HttpCache::Transaction::DoCompletePartialCacheValidation(int result
) {
1479 // This is the end of the request.
1480 if (mode_
& WRITE
) {
1481 DoneWritingToEntry(true);
1483 cache_
->DoneReadingFromEntry(entry_
, this);
1492 partial_
->PrepareCacheValidation(entry_
->disk_entry
,
1493 &custom_request_
->extra_headers
);
1495 if (reading_
&& partial_
->IsCurrentRangeCached()) {
1496 next_state_
= STATE_CACHE_READ_DATA
;
1500 return BeginCacheValidation();
1503 // We received 304 or 206 and we want to update the cached response headers.
1504 int HttpCache::Transaction::DoUpdateCachedResponse() {
1505 next_state_
= STATE_UPDATE_CACHED_RESPONSE_COMPLETE
;
1507 // Update cached response based on headers in new_response.
1508 // TODO(wtc): should we update cached certificate (response_.ssl_info), too?
1509 response_
.headers
->Update(*new_response_
->headers
.get());
1510 response_
.response_time
= new_response_
->response_time
;
1511 response_
.request_time
= new_response_
->request_time
;
1512 response_
.network_accessed
= new_response_
->network_accessed
;
1514 if (response_
.headers
->HasHeaderValue("cache-control", "no-store")) {
1515 if (!entry_
->doomed
) {
1516 int ret
= cache_
->DoomEntry(cache_key_
, NULL
);
1520 // If we are already reading, we already updated the headers for this
1521 // request; doing it again will change Content-Length.
1523 target_state_
= STATE_UPDATE_CACHED_RESPONSE_COMPLETE
;
1524 next_state_
= STATE_CACHE_WRITE_RESPONSE
;
1531 int HttpCache::Transaction::DoUpdateCachedResponseComplete(int result
) {
1532 if (mode_
== UPDATE
) {
1533 DCHECK(!handling_206_
);
1534 // We got a "not modified" response and already updated the corresponding
1535 // cache entry above.
1537 // By closing the cached entry now, we make sure that the 304 rather than
1538 // the cached 200 response, is what will be returned to the user.
1539 DoneWritingToEntry(true);
1540 } else if (entry_
&& !handling_206_
) {
1541 DCHECK_EQ(READ_WRITE
, mode_
);
1542 if (!partial_
.get() || partial_
->IsLastRange()) {
1543 cache_
->ConvertWriterToReader(entry_
);
1546 // We no longer need the network transaction, so destroy it.
1547 final_upload_progress_
= network_trans_
->GetUploadProgress();
1548 ResetNetworkTransaction();
1549 } else if (entry_
&& handling_206_
&& truncated_
&&
1550 partial_
->initial_validation()) {
1551 // We just finished the validation of a truncated entry, and the server
1552 // is willing to resume the operation. Now we go back and start serving
1553 // the first part to the user.
1554 ResetNetworkTransaction();
1555 new_response_
= NULL
;
1556 next_state_
= STATE_START_PARTIAL_CACHE_VALIDATION
;
1557 partial_
->SetRangeToStartDownload();
1560 next_state_
= STATE_OVERWRITE_CACHED_RESPONSE
;
1564 int HttpCache::Transaction::DoOverwriteCachedResponse() {
1566 next_state_
= STATE_PARTIAL_HEADERS_RECEIVED
;
1570 // We change the value of Content-Length for partial content.
1571 if (handling_206_
&& partial_
.get())
1572 partial_
->FixContentLength(new_response_
->headers
.get());
1574 response_
= *new_response_
;
1576 if (request_
->method
== "HEAD") {
1577 // This response is replacing the cached one.
1578 DoneWritingToEntry(false);
1580 new_response_
= NULL
;
1584 target_state_
= STATE_TRUNCATE_CACHED_DATA
;
1585 next_state_
= truncated_
? STATE_CACHE_WRITE_TRUNCATED_RESPONSE
:
1586 STATE_CACHE_WRITE_RESPONSE
;
1590 int HttpCache::Transaction::DoTruncateCachedData() {
1591 next_state_
= STATE_TRUNCATE_CACHED_DATA_COMPLETE
;
1594 if (net_log_
.IsLogging())
1595 net_log_
.BeginEvent(NetLog::TYPE_HTTP_CACHE_WRITE_DATA
);
1596 // Truncate the stream.
1597 return WriteToEntry(kResponseContentIndex
, 0, NULL
, 0, io_callback_
);
1600 int HttpCache::Transaction::DoTruncateCachedDataComplete(int result
) {
1602 if (net_log_
.IsLogging()) {
1603 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_HTTP_CACHE_WRITE_DATA
,
1608 next_state_
= STATE_TRUNCATE_CACHED_METADATA
;
1612 int HttpCache::Transaction::DoTruncateCachedMetadata() {
1613 next_state_
= STATE_TRUNCATE_CACHED_METADATA_COMPLETE
;
1617 if (net_log_
.IsLogging())
1618 net_log_
.BeginEvent(NetLog::TYPE_HTTP_CACHE_WRITE_INFO
);
1619 return WriteToEntry(kMetadataIndex
, 0, NULL
, 0, io_callback_
);
1622 int HttpCache::Transaction::DoTruncateCachedMetadataComplete(int result
) {
1624 if (net_log_
.IsLogging()) {
1625 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_HTTP_CACHE_WRITE_INFO
,
1630 next_state_
= STATE_PARTIAL_HEADERS_RECEIVED
;
1634 int HttpCache::Transaction::DoPartialHeadersReceived() {
1635 new_response_
= NULL
;
1636 if (entry_
&& !partial_
.get() &&
1637 entry_
->disk_entry
->GetDataSize(kMetadataIndex
))
1638 next_state_
= STATE_CACHE_READ_METADATA
;
1640 if (!partial_
.get())
1644 if (network_trans_
.get()) {
1645 next_state_
= STATE_NETWORK_READ
;
1647 next_state_
= STATE_CACHE_READ_DATA
;
1649 } else if (mode_
!= NONE
) {
1650 // We are about to return the headers for a byte-range request to the user,
1651 // so let's fix them.
1652 partial_
->FixResponseHeaders(response_
.headers
.get(), true);
1657 int HttpCache::Transaction::DoCacheReadResponse() {
1659 next_state_
= STATE_CACHE_READ_RESPONSE_COMPLETE
;
1661 io_buf_len_
= entry_
->disk_entry
->GetDataSize(kResponseInfoIndex
);
1662 read_buf_
= new IOBuffer(io_buf_len_
);
1664 net_log_
.BeginEvent(NetLog::TYPE_HTTP_CACHE_READ_INFO
);
1665 return entry_
->disk_entry
->ReadData(kResponseInfoIndex
, 0, read_buf_
.get(),
1666 io_buf_len_
, io_callback_
);
1669 int HttpCache::Transaction::DoCacheReadResponseComplete(int result
) {
1670 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_HTTP_CACHE_READ_INFO
, result
);
1671 if (result
!= io_buf_len_
||
1672 !HttpCache::ParseResponseInfo(read_buf_
->data(), io_buf_len_
,
1673 &response_
, &truncated_
)) {
1674 return OnCacheReadError(result
, true);
1677 // cert_cache() will be null if the CertCacheTrial field trial is disabled.
1678 if (cache_
->cert_cache() && response_
.ssl_info
.is_valid())
1681 // Some resources may have slipped in as truncated when they're not.
1682 int current_size
= entry_
->disk_entry
->GetDataSize(kResponseContentIndex
);
1683 if (response_
.headers
->GetContentLength() == current_size
)
1686 // We now have access to the cache entry.
1688 // o if we are a reader for the transaction, then we can start reading the
1691 // o if we can read or write, then we should check if the cache entry needs
1692 // to be validated and then issue a network request if needed or just read
1693 // from the cache if the cache entry is already valid.
1695 // o if we are set to UPDATE, then we are handling an externally
1696 // conditionalized request (if-modified-since / if-none-match). We check
1697 // if the request headers define a validation request.
1701 UpdateTransactionPattern(PATTERN_ENTRY_USED
);
1702 result
= BeginCacheRead();
1705 result
= BeginPartialCacheValidation();
1708 result
= BeginExternallyConditionalizedRequest();
1713 result
= ERR_FAILED
;
1718 int HttpCache::Transaction::DoCacheWriteResponse() {
1720 if (net_log_
.IsLogging())
1721 net_log_
.BeginEvent(NetLog::TYPE_HTTP_CACHE_WRITE_INFO
);
1723 return WriteResponseInfoToEntry(false);
1726 int HttpCache::Transaction::DoCacheWriteTruncatedResponse() {
1728 if (net_log_
.IsLogging())
1729 net_log_
.BeginEvent(NetLog::TYPE_HTTP_CACHE_WRITE_INFO
);
1731 return WriteResponseInfoToEntry(true);
1734 int HttpCache::Transaction::DoCacheWriteResponseComplete(int result
) {
1735 next_state_
= target_state_
;
1736 target_state_
= STATE_NONE
;
1739 if (net_log_
.IsLogging()) {
1740 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_HTTP_CACHE_WRITE_INFO
,
1744 // Balance the AddRef from WriteResponseInfoToEntry.
1745 if (result
!= io_buf_len_
) {
1746 DLOG(ERROR
) << "failed to write response info to cache";
1747 DoneWritingToEntry(false);
1752 int HttpCache::Transaction::DoCacheReadMetadata() {
1754 DCHECK(!response_
.metadata
.get());
1755 next_state_
= STATE_CACHE_READ_METADATA_COMPLETE
;
1757 response_
.metadata
=
1758 new IOBufferWithSize(entry_
->disk_entry
->GetDataSize(kMetadataIndex
));
1760 net_log_
.BeginEvent(NetLog::TYPE_HTTP_CACHE_READ_INFO
);
1761 return entry_
->disk_entry
->ReadData(kMetadataIndex
, 0,
1762 response_
.metadata
.get(),
1763 response_
.metadata
->size(),
1767 int HttpCache::Transaction::DoCacheReadMetadataComplete(int result
) {
1768 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_HTTP_CACHE_READ_INFO
, result
);
1769 if (result
!= response_
.metadata
->size())
1770 return OnCacheReadError(result
, false);
1774 int HttpCache::Transaction::DoCacheQueryData() {
1775 next_state_
= STATE_CACHE_QUERY_DATA_COMPLETE
;
1776 return entry_
->disk_entry
->ReadyForSparseIO(io_callback_
);
1779 int HttpCache::Transaction::DoCacheQueryDataComplete(int result
) {
1780 if (result
== ERR_NOT_IMPLEMENTED
) {
1781 // Restart the request overwriting the cache entry.
1782 // TODO(pasko): remove this workaround as soon as the SimpleBackendImpl
1783 // supports Sparse IO.
1784 return DoRestartPartialRequest();
1786 DCHECK_EQ(OK
, result
);
1788 return ERR_UNEXPECTED
;
1790 return ValidateEntryHeadersAndContinue();
1793 int HttpCache::Transaction::DoCacheReadData() {
1795 next_state_
= STATE_CACHE_READ_DATA_COMPLETE
;
1797 if (net_log_
.IsLogging())
1798 net_log_
.BeginEvent(NetLog::TYPE_HTTP_CACHE_READ_DATA
);
1799 if (partial_
.get()) {
1800 return partial_
->CacheRead(entry_
->disk_entry
, read_buf_
.get(), io_buf_len_
,
1804 return entry_
->disk_entry
->ReadData(kResponseContentIndex
, read_offset_
,
1805 read_buf_
.get(), io_buf_len_
,
1809 int HttpCache::Transaction::DoCacheReadDataComplete(int result
) {
1810 if (net_log_
.IsLogging()) {
1811 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_HTTP_CACHE_READ_DATA
,
1816 return ERR_UNEXPECTED
;
1818 if (partial_
.get()) {
1819 // Partial requests are confusing to report in histograms because they may
1820 // have multiple underlying requests.
1821 UpdateTransactionPattern(PATTERN_NOT_COVERED
);
1822 return DoPartialCacheReadCompleted(result
);
1826 read_offset_
+= result
;
1827 } else if (result
== 0) { // End of file.
1829 cache_
->DoneReadingFromEntry(entry_
, this);
1832 return OnCacheReadError(result
, false);
1837 int HttpCache::Transaction::DoCacheWriteData(int num_bytes
) {
1838 next_state_
= STATE_CACHE_WRITE_DATA_COMPLETE
;
1839 write_len_
= num_bytes
;
1841 if (net_log_
.IsLogging())
1842 net_log_
.BeginEvent(NetLog::TYPE_HTTP_CACHE_WRITE_DATA
);
1845 return AppendResponseDataToEntry(read_buf_
.get(), num_bytes
, io_callback_
);
1848 int HttpCache::Transaction::DoCacheWriteDataComplete(int result
) {
1850 if (net_log_
.IsLogging()) {
1851 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_HTTP_CACHE_WRITE_DATA
,
1855 // Balance the AddRef from DoCacheWriteData.
1857 return ERR_UNEXPECTED
;
1859 if (result
!= write_len_
) {
1860 DLOG(ERROR
) << "failed to write response data to cache";
1861 DoneWritingToEntry(false);
1863 // We want to ignore errors writing to disk and just keep reading from
1865 result
= write_len_
;
1866 } else if (!done_reading_
&& entry_
) {
1867 int current_size
= entry_
->disk_entry
->GetDataSize(kResponseContentIndex
);
1868 int64 body_size
= response_
.headers
->GetContentLength();
1869 if (body_size
>= 0 && body_size
<= current_size
)
1870 done_reading_
= true;
1873 if (partial_
.get()) {
1874 // This may be the last request.
1875 if (!(result
== 0 && !truncated_
&&
1876 (partial_
->IsLastRange() || mode_
== WRITE
)))
1877 return DoPartialNetworkReadCompleted(result
);
1881 // End of file. This may be the result of a connection problem so see if we
1882 // have to keep the entry around to be flagged as truncated later on.
1883 if (done_reading_
|| !entry_
|| partial_
.get() ||
1884 response_
.headers
->GetContentLength() <= 0)
1885 DoneWritingToEntry(true);
1891 //-----------------------------------------------------------------------------
1893 void HttpCache::Transaction::ReadCertChain() {
1895 GetCacheKeyForCert(response_
.ssl_info
.cert
->os_cert_handle());
1896 const X509Certificate::OSCertHandles
& intermediates
=
1897 response_
.ssl_info
.cert
->GetIntermediateCertificates();
1898 int dist_from_root
= intermediates
.size();
1900 scoped_refptr
<SharedChainData
> shared_chain_data(
1901 new SharedChainData(intermediates
.size() + 1, TimeTicks::Now()));
1902 cache_
->cert_cache()->GetCertificate(key
,
1903 base::Bind(&OnCertReadIOComplete
,
1906 shared_chain_data
));
1908 for (X509Certificate::OSCertHandles::const_iterator it
=
1909 intermediates
.begin();
1910 it
!= intermediates
.end();
1913 key
= GetCacheKeyForCert(*it
);
1914 cache_
->cert_cache()->GetCertificate(key
,
1915 base::Bind(&OnCertReadIOComplete
,
1917 false /* is not leaf */,
1918 shared_chain_data
));
1920 DCHECK_EQ(0, dist_from_root
);
1923 void HttpCache::Transaction::WriteCertChain() {
1924 const X509Certificate::OSCertHandles
& intermediates
=
1925 response_
.ssl_info
.cert
->GetIntermediateCertificates();
1926 int dist_from_root
= intermediates
.size();
1928 scoped_refptr
<SharedChainData
> shared_chain_data(
1929 new SharedChainData(intermediates
.size() + 1, TimeTicks::Now()));
1930 cache_
->cert_cache()->SetCertificate(
1931 response_
.ssl_info
.cert
->os_cert_handle(),
1932 base::Bind(&OnCertWriteIOComplete
,
1935 shared_chain_data
));
1936 for (X509Certificate::OSCertHandles::const_iterator it
=
1937 intermediates
.begin();
1938 it
!= intermediates
.end();
1941 cache_
->cert_cache()->SetCertificate(*it
,
1942 base::Bind(&OnCertWriteIOComplete
,
1944 false /* is not leaf */,
1945 shared_chain_data
));
1947 DCHECK_EQ(0, dist_from_root
);
1950 void HttpCache::Transaction::SetRequest(const BoundNetLog
& net_log
,
1951 const HttpRequestInfo
* request
) {
1954 effective_load_flags_
= request_
->load_flags
;
1956 switch (cache_
->mode()) {
1960 // When in record mode, we want to NEVER load from the cache.
1961 // The reason for this is because we save the Set-Cookie headers
1962 // (intentionally). If we read from the cache, we replay them
1964 effective_load_flags_
|= LOAD_BYPASS_CACHE
;
1967 // When in playback mode, we want to load exclusively from the cache.
1968 effective_load_flags_
|= LOAD_ONLY_FROM_CACHE
;
1971 effective_load_flags_
|= LOAD_DISABLE_CACHE
;
1975 // Some headers imply load flags. The order here is significant.
1977 // LOAD_DISABLE_CACHE : no cache read or write
1978 // LOAD_BYPASS_CACHE : no cache read
1979 // LOAD_VALIDATE_CACHE : no cache read unless validation
1981 // The former modes trump latter modes, so if we find a matching header we
1982 // can stop iterating kSpecialHeaders.
1984 static const struct {
1985 const HeaderNameAndValue
* search
;
1987 } kSpecialHeaders
[] = {
1988 { kPassThroughHeaders
, LOAD_DISABLE_CACHE
},
1989 { kForceFetchHeaders
, LOAD_BYPASS_CACHE
},
1990 { kForceValidateHeaders
, LOAD_VALIDATE_CACHE
},
1993 bool range_found
= false;
1994 bool external_validation_error
= false;
1996 if (request_
->extra_headers
.HasHeader(HttpRequestHeaders::kRange
))
1999 for (size_t i
= 0; i
< ARRAYSIZE_UNSAFE(kSpecialHeaders
); ++i
) {
2000 if (HeaderMatches(request_
->extra_headers
, kSpecialHeaders
[i
].search
)) {
2001 effective_load_flags_
|= kSpecialHeaders
[i
].load_flag
;
2006 // Check for conditionalization headers which may correspond with a
2007 // cache validation request.
2008 for (size_t i
= 0; i
< arraysize(kValidationHeaders
); ++i
) {
2009 const ValidationHeaderInfo
& info
= kValidationHeaders
[i
];
2010 std::string validation_value
;
2011 if (request_
->extra_headers
.GetHeader(
2012 info
.request_header_name
, &validation_value
)) {
2013 if (!external_validation_
.values
[i
].empty() ||
2014 validation_value
.empty()) {
2015 external_validation_error
= true;
2017 external_validation_
.values
[i
] = validation_value
;
2018 external_validation_
.initialized
= true;
2022 // We don't support ranges and validation headers.
2023 if (range_found
&& external_validation_
.initialized
) {
2024 LOG(WARNING
) << "Byte ranges AND validation headers found.";
2025 effective_load_flags_
|= LOAD_DISABLE_CACHE
;
2028 // If there is more than one validation header, we can't treat this request as
2029 // a cache validation, since we don't know for sure which header the server
2030 // will give us a response for (and they could be contradictory).
2031 if (external_validation_error
) {
2032 LOG(WARNING
) << "Multiple or malformed validation headers found.";
2033 effective_load_flags_
|= LOAD_DISABLE_CACHE
;
2036 if (range_found
&& !(effective_load_flags_
& LOAD_DISABLE_CACHE
)) {
2037 UpdateTransactionPattern(PATTERN_NOT_COVERED
);
2038 partial_
.reset(new PartialData
);
2039 if (request_
->method
== "GET" && partial_
->Init(request_
->extra_headers
)) {
2040 // We will be modifying the actual range requested to the server, so
2041 // let's remove the header here.
2042 custom_request_
.reset(new HttpRequestInfo(*request_
));
2043 custom_request_
->extra_headers
.RemoveHeader(HttpRequestHeaders::kRange
);
2044 request_
= custom_request_
.get();
2045 partial_
->SetHeaders(custom_request_
->extra_headers
);
2047 // The range is invalid or we cannot handle it properly.
2048 VLOG(1) << "Invalid byte range found.";
2049 effective_load_flags_
|= LOAD_DISABLE_CACHE
;
2050 partial_
.reset(NULL
);
2055 bool HttpCache::Transaction::ShouldPassThrough() {
2056 // We may have a null disk_cache if there is an error we cannot recover from,
2057 // like not enough disk space, or sharing violations.
2058 if (!cache_
->disk_cache_
.get())
2061 // When using the record/playback modes, we always use the cache
2062 // and we never pass through.
2063 if (cache_
->mode() == RECORD
|| cache_
->mode() == PLAYBACK
)
2066 if (effective_load_flags_
& LOAD_DISABLE_CACHE
)
2069 if (request_
->method
== "GET" || request_
->method
== "HEAD")
2072 if (request_
->method
== "POST" && request_
->upload_data_stream
&&
2073 request_
->upload_data_stream
->identifier()) {
2077 if (request_
->method
== "PUT" && request_
->upload_data_stream
)
2080 if (request_
->method
== "DELETE")
2086 int HttpCache::Transaction::BeginCacheRead() {
2087 // We don't support any combination of LOAD_ONLY_FROM_CACHE and byte ranges.
2088 if (response_
.headers
->response_code() == 206 || partial_
.get()) {
2090 return ERR_CACHE_MISS
;
2093 if (request_
->method
== "HEAD")
2094 FixHeadersForHead();
2096 // We don't have the whole resource.
2098 return ERR_CACHE_MISS
;
2100 if (entry_
->disk_entry
->GetDataSize(kMetadataIndex
))
2101 next_state_
= STATE_CACHE_READ_METADATA
;
2106 int HttpCache::Transaction::BeginCacheValidation() {
2107 DCHECK(mode_
== READ_WRITE
);
2109 bool skip_validation
= !RequiresValidation();
2111 if (request_
->method
== "HEAD" &&
2112 (truncated_
|| response_
.headers
->response_code() == 206)) {
2114 if (skip_validation
)
2115 return SetupEntryForRead();
2118 next_state_
= STATE_SEND_REQUEST
;
2124 // Truncated entries can cause partial gets, so we shouldn't record this
2125 // load in histograms.
2126 UpdateTransactionPattern(PATTERN_NOT_COVERED
);
2127 skip_validation
= !partial_
->initial_validation();
2130 if (partial_
.get() && (is_sparse_
|| truncated_
) &&
2131 (!partial_
->IsCurrentRangeCached() || invalid_range_
)) {
2132 // Force revalidation for sparse or truncated entries. Note that we don't
2133 // want to ignore the regular validation logic just because a byte range was
2134 // part of the request.
2135 skip_validation
= false;
2138 if (skip_validation
) {
2139 UpdateTransactionPattern(PATTERN_ENTRY_USED
);
2140 RecordOfflineStatus(effective_load_flags_
, OFFLINE_STATUS_FRESH_CACHE
);
2141 return SetupEntryForRead();
2143 // Make the network request conditional, to see if we may reuse our cached
2144 // response. If we cannot do so, then we just resort to a normal fetch.
2145 // Our mode remains READ_WRITE for a conditional request. Even if the
2146 // conditionalization fails, we don't switch to WRITE mode until we
2147 // know we won't be falling back to using the cache entry in the
2148 // LOAD_FROM_CACHE_IF_OFFLINE case.
2149 if (!ConditionalizeRequest()) {
2150 couldnt_conditionalize_request_
= true;
2151 UpdateTransactionPattern(PATTERN_ENTRY_CANT_CONDITIONALIZE
);
2153 return DoRestartPartialRequest();
2155 DCHECK_NE(206, response_
.headers
->response_code());
2157 next_state_
= STATE_SEND_REQUEST
;
2162 int HttpCache::Transaction::BeginPartialCacheValidation() {
2163 DCHECK(mode_
== READ_WRITE
);
2165 if (response_
.headers
->response_code() != 206 && !partial_
.get() &&
2167 return BeginCacheValidation();
2170 // Partial requests should not be recorded in histograms.
2171 UpdateTransactionPattern(PATTERN_NOT_COVERED
);
2172 if (range_requested_
) {
2173 next_state_
= STATE_CACHE_QUERY_DATA
;
2177 // The request is not for a range, but we have stored just ranges.
2179 if (request_
->method
== "HEAD")
2180 return BeginCacheValidation();
2182 partial_
.reset(new PartialData());
2183 partial_
->SetHeaders(request_
->extra_headers
);
2184 if (!custom_request_
.get()) {
2185 custom_request_
.reset(new HttpRequestInfo(*request_
));
2186 request_
= custom_request_
.get();
2189 return ValidateEntryHeadersAndContinue();
2192 // This should only be called once per request.
2193 int HttpCache::Transaction::ValidateEntryHeadersAndContinue() {
2194 DCHECK(mode_
== READ_WRITE
);
2196 if (!partial_
->UpdateFromStoredHeaders(
2197 response_
.headers
.get(), entry_
->disk_entry
, truncated_
)) {
2198 return DoRestartPartialRequest();
2201 if (response_
.headers
->response_code() == 206)
2204 if (!partial_
->IsRequestedRangeOK()) {
2205 // The stored data is fine, but the request may be invalid.
2206 invalid_range_
= true;
2209 next_state_
= STATE_START_PARTIAL_CACHE_VALIDATION
;
2213 int HttpCache::Transaction::BeginExternallyConditionalizedRequest() {
2214 DCHECK_EQ(UPDATE
, mode_
);
2215 DCHECK(external_validation_
.initialized
);
2217 for (size_t i
= 0; i
< arraysize(kValidationHeaders
); i
++) {
2218 if (external_validation_
.values
[i
].empty())
2220 // Retrieve either the cached response's "etag" or "last-modified" header.
2221 std::string validator
;
2222 response_
.headers
->EnumerateHeader(
2224 kValidationHeaders
[i
].related_response_header_name
,
2227 if (response_
.headers
->response_code() != 200 || truncated_
||
2228 validator
.empty() || validator
!= external_validation_
.values
[i
]) {
2229 // The externally conditionalized request is not a validation request
2230 // for our existing cache entry. Proceed with caching disabled.
2231 UpdateTransactionPattern(PATTERN_NOT_COVERED
);
2232 DoneWritingToEntry(true);
2236 // TODO(ricea): This calculation is expensive to perform just to collect
2237 // statistics. Either remove it or use the result, depending on the result of
2239 ExternallyConditionalizedType type
=
2240 EXTERNALLY_CONDITIONALIZED_CACHE_USABLE
;
2242 type
= EXTERNALLY_CONDITIONALIZED_MISMATCHED_VALIDATORS
;
2243 else if (RequiresValidation())
2244 type
= EXTERNALLY_CONDITIONALIZED_CACHE_REQUIRES_VALIDATION
;
2246 // TODO(ricea): Add CACHE_USABLE_STALE once stale-while-revalidate CL landed.
2247 // TODO(ricea): Either remove this histogram or make it permanent by M40.
2248 UMA_HISTOGRAM_ENUMERATION("HttpCache.ExternallyConditionalized",
2250 EXTERNALLY_CONDITIONALIZED_MAX
);
2252 next_state_
= STATE_SEND_REQUEST
;
2256 int HttpCache::Transaction::RestartNetworkRequest() {
2257 DCHECK(mode_
& WRITE
|| mode_
== NONE
);
2258 DCHECK(network_trans_
.get());
2259 DCHECK_EQ(STATE_NONE
, next_state_
);
2261 next_state_
= STATE_SEND_REQUEST_COMPLETE
;
2262 int rv
= network_trans_
->RestartIgnoringLastError(io_callback_
);
2263 if (rv
!= ERR_IO_PENDING
)
2268 int HttpCache::Transaction::RestartNetworkRequestWithCertificate(
2269 X509Certificate
* client_cert
) {
2270 DCHECK(mode_
& WRITE
|| mode_
== NONE
);
2271 DCHECK(network_trans_
.get());
2272 DCHECK_EQ(STATE_NONE
, next_state_
);
2274 next_state_
= STATE_SEND_REQUEST_COMPLETE
;
2275 int rv
= network_trans_
->RestartWithCertificate(client_cert
, io_callback_
);
2276 if (rv
!= ERR_IO_PENDING
)
2281 int HttpCache::Transaction::RestartNetworkRequestWithAuth(
2282 const AuthCredentials
& credentials
) {
2283 DCHECK(mode_
& WRITE
|| mode_
== NONE
);
2284 DCHECK(network_trans_
.get());
2285 DCHECK_EQ(STATE_NONE
, next_state_
);
2287 next_state_
= STATE_SEND_REQUEST_COMPLETE
;
2288 int rv
= network_trans_
->RestartWithAuth(credentials
, io_callback_
);
2289 if (rv
!= ERR_IO_PENDING
)
2294 bool HttpCache::Transaction::RequiresValidation() {
2295 // TODO(darin): need to do more work here:
2296 // - make sure we have a matching request method
2297 // - watch out for cached responses that depend on authentication
2299 // In playback mode, nothing requires validation.
2300 if (cache_
->mode() == net::HttpCache::PLAYBACK
)
2303 if (response_
.vary_data
.is_valid() &&
2304 !response_
.vary_data
.MatchesRequest(*request_
,
2305 *response_
.headers
.get())) {
2306 vary_mismatch_
= true;
2310 if (effective_load_flags_
& LOAD_PREFERRING_CACHE
)
2313 if (effective_load_flags_
& LOAD_VALIDATE_CACHE
)
2316 if (request_
->method
== "PUT" || request_
->method
== "DELETE")
2319 if (response_
.headers
->RequiresValidation(
2320 response_
.request_time
, response_
.response_time
, Time::Now())) {
2327 bool HttpCache::Transaction::ConditionalizeRequest() {
2328 DCHECK(response_
.headers
.get());
2330 if (request_
->method
== "PUT" || request_
->method
== "DELETE")
2333 // This only makes sense for cached 200 or 206 responses.
2334 if (response_
.headers
->response_code() != 200 &&
2335 response_
.headers
->response_code() != 206) {
2339 if (response_
.headers
->response_code() == 206 &&
2340 !response_
.headers
->HasStrongValidators()) {
2344 // Just use the first available ETag and/or Last-Modified header value.
2345 // TODO(darin): Or should we use the last?
2347 std::string etag_value
;
2348 if (response_
.headers
->GetHttpVersion() >= HttpVersion(1, 1))
2349 response_
.headers
->EnumerateHeader(NULL
, "etag", &etag_value
);
2351 std::string last_modified_value
;
2352 if (!vary_mismatch_
) {
2353 response_
.headers
->EnumerateHeader(NULL
, "last-modified",
2354 &last_modified_value
);
2357 if (etag_value
.empty() && last_modified_value
.empty())
2360 if (!partial_
.get()) {
2361 // Need to customize the request, so this forces us to allocate :(
2362 custom_request_
.reset(new HttpRequestInfo(*request_
));
2363 request_
= custom_request_
.get();
2365 DCHECK(custom_request_
.get());
2367 bool use_if_range
= partial_
.get() && !partial_
->IsCurrentRangeCached() &&
2370 if (!use_if_range
) {
2371 // stale-while-revalidate is not useful when we only have a partial response
2372 // cached, so don't set the header in that case.
2373 TimeDelta stale_while_revalidate
;
2374 if (response_
.headers
->GetStaleWhileRevalidateValue(
2375 &stale_while_revalidate
) &&
2376 stale_while_revalidate
> TimeDelta()) {
2378 response_
.headers
->GetFreshnessLifetime(response_
.response_time
);
2379 TimeDelta current_age
= response_
.headers
->GetCurrentAge(
2380 response_
.request_time
, response_
.response_time
, Time::Now());
2382 custom_request_
->extra_headers
.SetHeader(
2384 base::StringPrintf("max-age=%" PRId64
2385 ",stale-while-revalidate=%" PRId64
",age=%" PRId64
,
2386 max_age
.InSeconds(),
2387 stale_while_revalidate
.InSeconds(),
2388 current_age
.InSeconds()));
2392 if (!etag_value
.empty()) {
2394 // We don't want to switch to WRITE mode if we don't have this block of a
2395 // byte-range request because we may have other parts cached.
2396 custom_request_
->extra_headers
.SetHeader(
2397 HttpRequestHeaders::kIfRange
, etag_value
);
2399 custom_request_
->extra_headers
.SetHeader(
2400 HttpRequestHeaders::kIfNoneMatch
, etag_value
);
2402 // For byte-range requests, make sure that we use only one way to validate
2404 if (partial_
.get() && !partial_
->IsCurrentRangeCached())
2408 if (!last_modified_value
.empty()) {
2410 custom_request_
->extra_headers
.SetHeader(
2411 HttpRequestHeaders::kIfRange
, last_modified_value
);
2413 custom_request_
->extra_headers
.SetHeader(
2414 HttpRequestHeaders::kIfModifiedSince
, last_modified_value
);
2421 // We just received some headers from the server. We may have asked for a range,
2422 // in which case partial_ has an object. This could be the first network request
2423 // we make to fulfill the original request, or we may be already reading (from
2424 // the net and / or the cache). If we are not expecting a certain response, we
2425 // just bypass the cache for this request (but again, maybe we are reading), and
2426 // delete partial_ (so we are not able to "fix" the headers that we return to
2427 // the user). This results in either a weird response for the caller (we don't
2428 // expect it after all), or maybe a range that was not exactly what it was asked
2431 // If the server is simply telling us that the resource has changed, we delete
2432 // the cached entry and restart the request as the caller intended (by returning
2433 // false from this method). However, we may not be able to do that at any point,
2434 // for instance if we already returned the headers to the user.
2436 // WARNING: Whenever this code returns false, it has to make sure that the next
2437 // time it is called it will return true so that we don't keep retrying the
2439 bool HttpCache::Transaction::ValidatePartialResponse() {
2440 const HttpResponseHeaders
* headers
= new_response_
->headers
.get();
2441 int response_code
= headers
->response_code();
2442 bool partial_response
= (response_code
== 206);
2443 handling_206_
= false;
2445 if (!entry_
|| request_
->method
!= "GET")
2448 if (invalid_range_
) {
2449 // We gave up trying to match this request with the stored data. If the
2450 // server is ok with the request, delete the entry, otherwise just ignore
2453 if (partial_response
|| response_code
== 200) {
2454 DoomPartialEntry(true);
2457 if (response_code
== 304)
2459 IgnoreRangeRequest();
2464 if (!partial_
.get()) {
2465 // We are not expecting 206 but we may have one.
2466 if (partial_response
)
2467 IgnoreRangeRequest();
2472 // TODO(rvargas): Do we need to consider other results here?.
2473 bool failure
= response_code
== 200 || response_code
== 416;
2475 if (partial_
->IsCurrentRangeCached()) {
2476 // We asked for "If-None-Match: " so a 206 means a new object.
2477 if (partial_response
)
2480 if (response_code
== 304 && partial_
->ResponseHeadersOK(headers
))
2483 // We asked for "If-Range: " so a 206 means just another range.
2484 if (partial_response
&& partial_
->ResponseHeadersOK(headers
)) {
2485 handling_206_
= true;
2489 if (!reading_
&& !is_sparse_
&& !partial_response
) {
2490 // See if we can ignore the fact that we issued a byte range request.
2491 // If the server sends 200, just store it. If it sends an error, redirect
2492 // or something else, we may store the response as long as we didn't have
2493 // anything already stored.
2494 if (response_code
== 200 ||
2495 (!truncated_
&& response_code
!= 304 && response_code
!= 416)) {
2496 // The server is sending something else, and we can save it.
2497 DCHECK((truncated_
&& !partial_
->IsLastRange()) || range_requested_
);
2504 // 304 is not expected here, but we'll spare the entry (unless it was
2511 // We cannot truncate this entry, it has to be deleted.
2512 UpdateTransactionPattern(PATTERN_NOT_COVERED
);
2513 DoomPartialEntry(false);
2515 if (!reading_
&& !partial_
->IsLastRange()) {
2516 // We'll attempt to issue another network request, this time without us
2517 // messing up the headers.
2518 partial_
->RestoreHeaders(&custom_request_
->extra_headers
);
2523 LOG(WARNING
) << "Failed to revalidate partial entry";
2528 IgnoreRangeRequest();
2532 void HttpCache::Transaction::IgnoreRangeRequest() {
2533 // We have a problem. We may or may not be reading already (in which case we
2534 // returned the headers), but we'll just pretend that this request is not
2535 // using the cache and see what happens. Most likely this is the first
2536 // response from the server (it's not changing its mind midway, right?).
2537 UpdateTransactionPattern(PATTERN_NOT_COVERED
);
2539 DoneWritingToEntry(mode_
!= WRITE
);
2540 else if (mode_
& READ
&& entry_
)
2541 cache_
->DoneReadingFromEntry(entry_
, this);
2543 partial_
.reset(NULL
);
2548 void HttpCache::Transaction::FixHeadersForHead() {
2549 if (response_
.headers
->response_code() == 206) {
2550 response_
.headers
->RemoveHeader("Content-Length");
2551 response_
.headers
->RemoveHeader("Content-Range");
2552 response_
.headers
->ReplaceStatusLine("HTTP/1.1 200 OK");
2556 void HttpCache::Transaction::FailRangeRequest() {
2557 response_
= *new_response_
;
2558 partial_
->FixResponseHeaders(response_
.headers
.get(), false);
2561 int HttpCache::Transaction::SetupEntryForRead() {
2563 ResetNetworkTransaction();
2564 if (partial_
.get()) {
2565 if (truncated_
|| is_sparse_
|| !invalid_range_
) {
2566 // We are going to return the saved response headers to the caller, so
2567 // we may need to adjust them first.
2568 next_state_
= STATE_PARTIAL_HEADERS_RECEIVED
;
2574 cache_
->ConvertWriterToReader(entry_
);
2577 if (request_
->method
== "HEAD")
2578 FixHeadersForHead();
2580 if (entry_
->disk_entry
->GetDataSize(kMetadataIndex
))
2581 next_state_
= STATE_CACHE_READ_METADATA
;
2586 int HttpCache::Transaction::ReadFromNetwork(IOBuffer
* data
, int data_len
) {
2588 io_buf_len_
= data_len
;
2589 next_state_
= STATE_NETWORK_READ
;
2593 int HttpCache::Transaction::ReadFromEntry(IOBuffer
* data
, int data_len
) {
2594 if (request_
->method
== "HEAD")
2598 io_buf_len_
= data_len
;
2599 next_state_
= STATE_CACHE_READ_DATA
;
2603 int HttpCache::Transaction::WriteToEntry(int index
, int offset
,
2604 IOBuffer
* data
, int data_len
,
2605 const CompletionCallback
& callback
) {
2610 if (!partial_
.get() || !data_len
) {
2611 rv
= entry_
->disk_entry
->WriteData(index
, offset
, data
, data_len
, callback
,
2614 rv
= partial_
->CacheWrite(entry_
->disk_entry
, data
, data_len
, callback
);
2619 int HttpCache::Transaction::WriteResponseInfoToEntry(bool truncated
) {
2620 next_state_
= STATE_CACHE_WRITE_RESPONSE_COMPLETE
;
2624 // Do not cache no-store content (unless we are record mode). Do not cache
2625 // content with cert errors either. This is to prevent not reporting net
2626 // errors when loading a resource from the cache. When we load a page over
2627 // HTTPS with a cert error we show an SSL blocking page. If the user clicks
2628 // proceed we reload the resource ignoring the errors. The loaded resource
2629 // is then cached. If that resource is subsequently loaded from the cache,
2630 // no net error is reported (even though the cert status contains the actual
2631 // errors) and no SSL blocking page is shown. An alternative would be to
2632 // reverse-map the cert status to a net error and replay the net error.
2633 if ((cache_
->mode() != RECORD
&&
2634 response_
.headers
->HasHeaderValue("cache-control", "no-store")) ||
2635 net::IsCertStatusError(response_
.ssl_info
.cert_status
)) {
2636 DoneWritingToEntry(false);
2637 if (net_log_
.IsLogging())
2638 net_log_
.EndEvent(NetLog::TYPE_HTTP_CACHE_WRITE_INFO
);
2642 // cert_cache() will be null if the CertCacheTrial field trial is disabled.
2643 if (cache_
->cert_cache() && response_
.ssl_info
.is_valid())
2646 // When writing headers, we normally only write the non-transient
2647 // headers; when in record mode, record everything.
2648 bool skip_transient_headers
= (cache_
->mode() != RECORD
);
2651 DCHECK_EQ(200, response_
.headers
->response_code());
2653 scoped_refptr
<PickledIOBuffer
> data(new PickledIOBuffer());
2654 response_
.Persist(data
->pickle(), skip_transient_headers
, truncated
);
2657 io_buf_len_
= data
->pickle()->size();
2658 return entry_
->disk_entry
->WriteData(kResponseInfoIndex
, 0, data
.get(),
2659 io_buf_len_
, io_callback_
, true);
2662 int HttpCache::Transaction::AppendResponseDataToEntry(
2663 IOBuffer
* data
, int data_len
, const CompletionCallback
& callback
) {
2664 if (!entry_
|| !data_len
)
2667 int current_size
= entry_
->disk_entry
->GetDataSize(kResponseContentIndex
);
2668 return WriteToEntry(kResponseContentIndex
, current_size
, data
, data_len
,
2672 void HttpCache::Transaction::DoneWritingToEntry(bool success
) {
2678 cache_
->DoneWritingToEntry(entry_
, success
);
2680 mode_
= NONE
; // switch to 'pass through' mode
2683 int HttpCache::Transaction::OnCacheReadError(int result
, bool restart
) {
2684 DLOG(ERROR
) << "ReadData failed: " << result
;
2685 const int result_for_histogram
= std::max(0, -result
);
2687 UMA_HISTOGRAM_SPARSE_SLOWLY("HttpCache.ReadErrorRestartable",
2688 result_for_histogram
);
2690 UMA_HISTOGRAM_SPARSE_SLOWLY("HttpCache.ReadErrorNonRestartable",
2691 result_for_histogram
);
2694 // Avoid using this entry in the future.
2696 cache_
->DoomActiveEntry(cache_key_
);
2700 DCHECK(!network_trans_
.get());
2701 cache_
->DoneWithEntry(entry_
, this, false);
2705 next_state_
= STATE_GET_BACKEND
;
2709 return ERR_CACHE_READ_FAILURE
;
2712 void HttpCache::Transaction::OnAddToEntryTimeout(base::TimeTicks start_time
) {
2713 if (entry_lock_waiting_since_
!= start_time
)
2716 DCHECK_EQ(next_state_
, STATE_ADD_TO_ENTRY_COMPLETE
);
2721 cache_
->RemovePendingTransaction(this);
2722 OnIOComplete(ERR_CACHE_LOCK_TIMEOUT
);
2725 void HttpCache::Transaction::DoomPartialEntry(bool delete_object
) {
2726 DVLOG(2) << "DoomPartialEntry";
2727 int rv
= cache_
->DoomEntry(cache_key_
, NULL
);
2729 cache_
->DoneWithEntry(entry_
, this, false);
2733 partial_
.reset(NULL
);
2736 int HttpCache::Transaction::DoPartialNetworkReadCompleted(int result
) {
2737 partial_
->OnNetworkReadCompleted(result
);
2740 // We need to move on to the next range.
2741 ResetNetworkTransaction();
2742 next_state_
= STATE_START_PARTIAL_CACHE_VALIDATION
;
2747 int HttpCache::Transaction::DoPartialCacheReadCompleted(int result
) {
2748 partial_
->OnCacheReadCompleted(result
);
2750 if (result
== 0 && mode_
== READ_WRITE
) {
2751 // We need to move on to the next range.
2752 next_state_
= STATE_START_PARTIAL_CACHE_VALIDATION
;
2753 } else if (result
< 0) {
2754 return OnCacheReadError(result
, false);
2759 int HttpCache::Transaction::DoRestartPartialRequest() {
2760 // The stored data cannot be used. Get rid of it and restart this request.
2761 // We need to also reset the |truncated_| flag as a new entry is created.
2762 DoomPartialEntry(!range_requested_
);
2765 next_state_
= STATE_INIT_ENTRY
;
2769 void HttpCache::Transaction::ResetNetworkTransaction() {
2770 DCHECK(!old_network_trans_load_timing_
);
2771 DCHECK(network_trans_
);
2772 LoadTimingInfo load_timing
;
2773 if (network_trans_
->GetLoadTimingInfo(&load_timing
))
2774 old_network_trans_load_timing_
.reset(new LoadTimingInfo(load_timing
));
2775 total_received_bytes_
+= network_trans_
->GetTotalReceivedBytes();
2776 network_trans_
.reset();
2779 // Histogram data from the end of 2010 show the following distribution of
2780 // response headers:
2782 // Content-Length............... 87%
2783 // Date......................... 98%
2784 // Last-Modified................ 49%
2785 // Etag......................... 19%
2786 // Accept-Ranges: bytes......... 25%
2787 // Accept-Ranges: none.......... 0.4%
2788 // Strong Validator............. 50%
2789 // Strong Validator + ranges.... 24%
2790 // Strong Validator + CL........ 49%
2792 bool HttpCache::Transaction::CanResume(bool has_data
) {
2793 // Double check that there is something worth keeping.
2794 if (has_data
&& !entry_
->disk_entry
->GetDataSize(kResponseContentIndex
))
2797 if (request_
->method
!= "GET")
2800 // Note that if this is a 206, content-length was already fixed after calling
2801 // PartialData::ResponseHeadersOK().
2802 if (response_
.headers
->GetContentLength() <= 0 ||
2803 response_
.headers
->HasHeaderValue("Accept-Ranges", "none") ||
2804 !response_
.headers
->HasStrongValidators()) {
2811 void HttpCache::Transaction::UpdateTransactionPattern(
2812 TransactionPattern new_transaction_pattern
) {
2813 if (transaction_pattern_
== PATTERN_NOT_COVERED
)
2815 DCHECK(transaction_pattern_
== PATTERN_UNDEFINED
||
2816 new_transaction_pattern
== PATTERN_NOT_COVERED
);
2817 transaction_pattern_
= new_transaction_pattern
;
2820 void HttpCache::Transaction::RecordHistograms() {
2821 DCHECK_NE(PATTERN_UNDEFINED
, transaction_pattern_
);
2822 if (!cache_
.get() || !cache_
->GetCurrentBackend() ||
2823 cache_
->GetCurrentBackend()->GetCacheType() != DISK_CACHE
||
2824 cache_
->mode() != NORMAL
|| request_
->method
!= "GET") {
2827 UMA_HISTOGRAM_ENUMERATION(
2828 "HttpCache.Pattern", transaction_pattern_
, PATTERN_MAX
);
2829 if (transaction_pattern_
== PATTERN_NOT_COVERED
)
2831 DCHECK(!range_requested_
);
2832 DCHECK(!first_cache_access_since_
.is_null());
2834 TimeDelta total_time
= base::TimeTicks::Now() - first_cache_access_since_
;
2836 UMA_HISTOGRAM_TIMES("HttpCache.AccessToDone", total_time
);
2838 bool did_send_request
= !send_request_since_
.is_null();
2840 (did_send_request
&&
2841 (transaction_pattern_
== PATTERN_ENTRY_NOT_CACHED
||
2842 transaction_pattern_
== PATTERN_ENTRY_VALIDATED
||
2843 transaction_pattern_
== PATTERN_ENTRY_UPDATED
||
2844 transaction_pattern_
== PATTERN_ENTRY_CANT_CONDITIONALIZE
)) ||
2845 (!did_send_request
&& transaction_pattern_
== PATTERN_ENTRY_USED
));
2847 if (!did_send_request
) {
2848 DCHECK(transaction_pattern_
== PATTERN_ENTRY_USED
);
2849 UMA_HISTOGRAM_TIMES("HttpCache.AccessToDone.Used", total_time
);
2853 TimeDelta before_send_time
= send_request_since_
- first_cache_access_since_
;
2854 int before_send_percent
=
2855 total_time
.ToInternalValue() == 0 ? 0
2856 : before_send_time
* 100 / total_time
;
2857 DCHECK_LE(0, before_send_percent
);
2858 DCHECK_GE(100, before_send_percent
);
2860 UMA_HISTOGRAM_TIMES("HttpCache.AccessToDone.SentRequest", total_time
);
2861 UMA_HISTOGRAM_TIMES("HttpCache.BeforeSend", before_send_time
);
2862 UMA_HISTOGRAM_PERCENTAGE("HttpCache.PercentBeforeSend", before_send_percent
);
2864 // TODO(gavinp): Remove or minimize these histograms, particularly the ones
2865 // below this comment after we have received initial data.
2866 switch (transaction_pattern_
) {
2867 case PATTERN_ENTRY_CANT_CONDITIONALIZE
: {
2868 UMA_HISTOGRAM_TIMES("HttpCache.BeforeSend.CantConditionalize",
2870 UMA_HISTOGRAM_PERCENTAGE("HttpCache.PercentBeforeSend.CantConditionalize",
2871 before_send_percent
);
2874 case PATTERN_ENTRY_NOT_CACHED
: {
2875 UMA_HISTOGRAM_TIMES("HttpCache.BeforeSend.NotCached", before_send_time
);
2876 UMA_HISTOGRAM_PERCENTAGE("HttpCache.PercentBeforeSend.NotCached",
2877 before_send_percent
);
2880 case PATTERN_ENTRY_VALIDATED
: {
2881 UMA_HISTOGRAM_TIMES("HttpCache.BeforeSend.Validated", before_send_time
);
2882 UMA_HISTOGRAM_PERCENTAGE("HttpCache.PercentBeforeSend.Validated",
2883 before_send_percent
);
2886 case PATTERN_ENTRY_UPDATED
: {
2887 UMA_HISTOGRAM_TIMES("HttpCache.BeforeSend.Updated", before_send_time
);
2888 UMA_HISTOGRAM_PERCENTAGE("HttpCache.PercentBeforeSend.Updated",
2889 before_send_percent
);
2897 void HttpCache::Transaction::OnIOComplete(int result
) {