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" // For OS_POSIX
16 #include "base/bind.h"
17 #include "base/callback_helpers.h"
18 #include "base/compiler_specific.h"
19 #include "base/format_macros.h"
20 #include "base/location.h"
21 #include "base/metrics/histogram_macros.h"
22 #include "base/metrics/sparse_histogram.h"
23 #include "base/profiler/scoped_tracker.h"
24 #include "base/single_thread_task_runner.h"
25 #include "base/strings/string_number_conversions.h" // For HexEncode.
26 #include "base/strings/string_piece.h"
27 #include "base/strings/string_util.h" // For LowerCaseEqualsASCII.
28 #include "base/strings/stringprintf.h"
29 #include "base/thread_task_runner_handle.h"
30 #include "base/time/clock.h"
31 #include "base/values.h"
32 #include "net/base/auth.h"
33 #include "net/base/load_flags.h"
34 #include "net/base/load_timing_info.h"
35 #include "net/base/net_errors.h"
36 #include "net/base/upload_data_stream.h"
37 #include "net/cert/cert_status_flags.h"
38 #include "net/cert/x509_certificate.h"
39 #include "net/disk_cache/disk_cache.h"
40 #include "net/http/disk_based_cert_cache.h"
41 #include "net/http/http_network_session.h"
42 #include "net/http/http_request_info.h"
43 #include "net/http/http_util.h"
44 #include "net/ssl/ssl_cert_request_info.h"
45 #include "net/ssl/ssl_config_service.h"
48 using base::TimeDelta
;
49 using base::TimeTicks
;
55 // TODO(ricea): Move this to HttpResponseHeaders once it is standardised.
56 static const char kFreshnessHeader
[] = "Resource-Freshness";
58 // Stores data relevant to the statistics of writing and reading entire
59 // certificate chains using DiskBasedCertCache. |num_pending_ops| is the number
60 // of certificates in the chain that have pending operations in the
61 // DiskBasedCertCache. |start_time| is the time that the read and write
62 // commands began being issued to the DiskBasedCertCache.
63 // TODO(brandonsalmon): Remove this when it is no longer necessary to
65 class SharedChainData
: public base::RefCounted
<SharedChainData
> {
67 SharedChainData(int num_ops
, TimeTicks start
)
68 : num_pending_ops(num_ops
), start_time(start
) {}
74 friend class base::RefCounted
<SharedChainData
>;
76 DISALLOW_COPY_AND_ASSIGN(SharedChainData
);
79 // Used to obtain a cache entry key for an OSCertHandle.
80 // TODO(brandonsalmon): Remove this when cache keys are stored
81 // and no longer have to be recomputed to retrieve the OSCertHandle
83 std::string
GetCacheKeyForCert(X509Certificate::OSCertHandle cert_handle
) {
84 SHA1HashValue fingerprint
=
85 X509Certificate::CalculateFingerprint(cert_handle
);
88 base::HexEncode(fingerprint
.data
, arraysize(fingerprint
.data
));
91 // |dist_from_root| indicates the position of the read certificate in the
92 // certificate chain, 0 indicating it is the root. |is_leaf| indicates
93 // whether or not the read certificate was the leaf of the chain.
94 // |shared_chain_data| contains data shared by each certificate in
96 void OnCertReadIOComplete(
99 const scoped_refptr
<SharedChainData
>& shared_chain_data
,
100 X509Certificate::OSCertHandle cert_handle
) {
101 // If |num_pending_ops| is one, this was the last pending read operation
102 // for this chain of certificates. The total time used to read the chain
103 // can be calculated by subtracting the starting time from Now().
104 shared_chain_data
->num_pending_ops
--;
105 if (!shared_chain_data
->num_pending_ops
) {
106 const TimeDelta read_chain_wait
=
107 TimeTicks::Now() - shared_chain_data
->start_time
;
108 UMA_HISTOGRAM_CUSTOM_TIMES("DiskBasedCertCache.ChainReadTime",
110 base::TimeDelta::FromMilliseconds(1),
111 base::TimeDelta::FromMinutes(10),
115 bool success
= (cert_handle
!= NULL
);
117 UMA_HISTOGRAM_BOOLEAN("DiskBasedCertCache.CertIoReadSuccessLeaf", success
);
120 UMA_HISTOGRAM_CUSTOM_COUNTS(
121 "DiskBasedCertCache.CertIoReadSuccess", dist_from_root
, 0, 10, 7);
123 UMA_HISTOGRAM_CUSTOM_COUNTS(
124 "DiskBasedCertCache.CertIoReadFailure", dist_from_root
, 0, 10, 7);
127 // |dist_from_root| indicates the position of the written certificate in the
128 // certificate chain, 0 indicating it is the root. |is_leaf| indicates
129 // whether or not the written certificate was the leaf of the chain.
130 // |shared_chain_data| contains data shared by each certificate in
132 void OnCertWriteIOComplete(
135 const scoped_refptr
<SharedChainData
>& shared_chain_data
,
136 const std::string
& key
) {
137 // If |num_pending_ops| is one, this was the last pending write operation
138 // for this chain of certificates. The total time used to write the chain
139 // can be calculated by subtracting the starting time from Now().
140 shared_chain_data
->num_pending_ops
--;
141 if (!shared_chain_data
->num_pending_ops
) {
142 const TimeDelta write_chain_wait
=
143 TimeTicks::Now() - shared_chain_data
->start_time
;
144 UMA_HISTOGRAM_CUSTOM_TIMES("DiskBasedCertCache.ChainWriteTime",
146 base::TimeDelta::FromMilliseconds(1),
147 base::TimeDelta::FromMinutes(10),
151 bool success
= !key
.empty();
153 UMA_HISTOGRAM_BOOLEAN("DiskBasedCertCache.CertIoWriteSuccessLeaf", success
);
156 UMA_HISTOGRAM_CUSTOM_COUNTS(
157 "DiskBasedCertCache.CertIoWriteSuccess", dist_from_root
, 0, 10, 7);
159 UMA_HISTOGRAM_CUSTOM_COUNTS(
160 "DiskBasedCertCache.CertIoWriteFailure", dist_from_root
, 0, 10, 7);
163 // From http://tools.ietf.org/html/draft-ietf-httpbis-p6-cache-21#section-6
164 // a "non-error response" is one with a 2xx (Successful) or 3xx
165 // (Redirection) status code.
166 bool NonErrorResponse(int status_code
) {
167 int status_code_range
= status_code
/ 100;
168 return status_code_range
== 2 || status_code_range
== 3;
171 void RecordNoStoreHeaderHistogram(int load_flags
,
172 const HttpResponseInfo
* response
) {
173 if (load_flags
& LOAD_MAIN_FRAME
) {
174 UMA_HISTOGRAM_BOOLEAN(
175 "Net.MainFrameNoStore",
176 response
->headers
->HasHeaderValue("cache-control", "no-store"));
180 enum ExternallyConditionalizedType
{
181 EXTERNALLY_CONDITIONALIZED_CACHE_REQUIRES_VALIDATION
,
182 EXTERNALLY_CONDITIONALIZED_CACHE_USABLE
,
183 EXTERNALLY_CONDITIONALIZED_MISMATCHED_VALIDATORS
,
184 EXTERNALLY_CONDITIONALIZED_MAX
189 struct HeaderNameAndValue
{
194 // If the request includes one of these request headers, then avoid caching
195 // to avoid getting confused.
196 static const HeaderNameAndValue kPassThroughHeaders
[] = {
197 { "if-unmodified-since", NULL
}, // causes unexpected 412s
198 { "if-match", NULL
}, // causes unexpected 412s
199 { "if-range", NULL
},
203 struct ValidationHeaderInfo
{
204 const char* request_header_name
;
205 const char* related_response_header_name
;
208 static const ValidationHeaderInfo kValidationHeaders
[] = {
209 { "if-modified-since", "last-modified" },
210 { "if-none-match", "etag" },
213 // If the request includes one of these request headers, then avoid reusing
214 // our cached copy if any.
215 static const HeaderNameAndValue kForceFetchHeaders
[] = {
216 { "cache-control", "no-cache" },
217 { "pragma", "no-cache" },
221 // If the request includes one of these request headers, then force our
222 // cached copy (if any) to be revalidated before reusing it.
223 static const HeaderNameAndValue kForceValidateHeaders
[] = {
224 { "cache-control", "max-age=0" },
228 static bool HeaderMatches(const HttpRequestHeaders
& headers
,
229 const HeaderNameAndValue
* search
) {
230 for (; search
->name
; ++search
) {
231 std::string header_value
;
232 if (!headers
.GetHeader(search
->name
, &header_value
))
238 HttpUtil::ValuesIterator
v(header_value
.begin(), header_value
.end(), ',');
239 while (v
.GetNext()) {
240 if (base::LowerCaseEqualsASCII(
241 base::StringPiece(v
.value_begin(), v
.value_end()), search
->value
))
248 //-----------------------------------------------------------------------------
250 HttpCache::Transaction::Transaction(RequestPriority priority
, HttpCache
* cache
)
251 : next_state_(STATE_NONE
),
254 cache_(cache
->GetWeakPtr()),
260 invalid_range_(false),
263 range_requested_(false),
264 handling_206_(false),
265 cache_pending_(false),
266 done_reading_(false),
267 vary_mismatch_(false),
268 couldnt_conditionalize_request_(false),
269 bypass_lock_for_test_(false),
270 fail_conditionalization_for_test_(false),
273 effective_load_flags_(0),
275 transaction_pattern_(PATTERN_UNDEFINED
),
276 total_received_bytes_(0),
277 total_sent_bytes_(0),
278 websocket_handshake_stream_base_create_helper_(NULL
),
279 weak_factory_(this) {
280 static_assert(HttpCache::Transaction::kNumValidationHeaders
==
281 arraysize(kValidationHeaders
),
282 "invalid number of validation headers");
284 io_callback_
= base::Bind(&Transaction::OnIOComplete
,
285 weak_factory_
.GetWeakPtr());
288 HttpCache::Transaction::~Transaction() {
289 // We may have to issue another IO, but we should never invoke the callback_
295 bool cancel_request
= reading_
&& response_
.headers
.get();
296 if (cancel_request
) {
298 entry_
->disk_entry
->CancelSparseIO();
300 cancel_request
&= (response_
.headers
->response_code() == 200);
304 cache_
->DoneWithEntry(entry_
, this, cancel_request
);
305 } else if (cache_pending_
) {
306 cache_
->RemovePendingTransaction(this);
311 int HttpCache::Transaction::WriteMetadata(IOBuffer
* buf
, int buf_len
,
312 const CompletionCallback
& callback
) {
314 DCHECK_GT(buf_len
, 0);
315 DCHECK(!callback
.is_null());
316 if (!cache_
.get() || !entry_
)
317 return ERR_UNEXPECTED
;
319 // We don't need to track this operation for anything.
320 // It could be possible to check if there is something already written and
321 // avoid writing again (it should be the same, right?), but let's allow the
322 // caller to "update" the contents with something new.
323 return entry_
->disk_entry
->WriteData(kMetadataIndex
, 0, buf
, buf_len
,
327 bool HttpCache::Transaction::AddTruncatedFlag() {
328 DCHECK(mode_
& WRITE
|| mode_
== NONE
);
330 // Don't set the flag for sparse entries.
331 if (partial_
&& !truncated_
)
334 if (!CanResume(true))
337 // We may have received the whole resource already.
342 next_state_
= STATE_CACHE_WRITE_TRUNCATED_RESPONSE
;
347 LoadState
HttpCache::Transaction::GetWriterLoadState() const {
348 if (network_trans_
.get())
349 return network_trans_
->GetLoadState();
350 if (entry_
|| !request_
)
351 return LOAD_STATE_IDLE
;
352 return LOAD_STATE_WAITING_FOR_CACHE
;
355 const BoundNetLog
& HttpCache::Transaction::net_log() const {
359 int HttpCache::Transaction::Start(const HttpRequestInfo
* request
,
360 const CompletionCallback
& callback
,
361 const BoundNetLog
& net_log
) {
363 DCHECK(!callback
.is_null());
365 // Ensure that we only have one asynchronous call at a time.
366 DCHECK(callback_
.is_null());
368 DCHECK(!network_trans_
.get());
370 DCHECK_EQ(next_state_
, STATE_NONE
);
373 return ERR_UNEXPECTED
;
375 SetRequest(net_log
, request
);
377 // We have to wait until the backend is initialized so we start the SM.
378 next_state_
= STATE_GET_BACKEND
;
381 // Setting this here allows us to check for the existence of a callback_ to
382 // determine if we are still inside Start.
383 if (rv
== ERR_IO_PENDING
)
384 callback_
= callback
;
389 int HttpCache::Transaction::RestartIgnoringLastError(
390 const CompletionCallback
& callback
) {
391 DCHECK(!callback
.is_null());
393 // Ensure that we only have one asynchronous call at a time.
394 DCHECK(callback_
.is_null());
397 return ERR_UNEXPECTED
;
399 int rv
= RestartNetworkRequest();
401 if (rv
== ERR_IO_PENDING
)
402 callback_
= callback
;
407 int HttpCache::Transaction::RestartWithCertificate(
408 X509Certificate
* client_cert
,
409 const CompletionCallback
& callback
) {
410 DCHECK(!callback
.is_null());
412 // Ensure that we only have one asynchronous call at a time.
413 DCHECK(callback_
.is_null());
416 return ERR_UNEXPECTED
;
418 int rv
= RestartNetworkRequestWithCertificate(client_cert
);
420 if (rv
== ERR_IO_PENDING
)
421 callback_
= callback
;
426 int HttpCache::Transaction::RestartWithAuth(
427 const AuthCredentials
& credentials
,
428 const CompletionCallback
& callback
) {
429 DCHECK(auth_response_
.headers
.get());
430 DCHECK(!callback
.is_null());
432 // Ensure that we only have one asynchronous call at a time.
433 DCHECK(callback_
.is_null());
436 return ERR_UNEXPECTED
;
438 // Clear the intermediate response since we are going to start over.
439 auth_response_
= HttpResponseInfo();
441 int rv
= RestartNetworkRequestWithAuth(credentials
);
443 if (rv
== ERR_IO_PENDING
)
444 callback_
= callback
;
449 bool HttpCache::Transaction::IsReadyToRestartForAuth() {
450 if (!network_trans_
.get())
452 return network_trans_
->IsReadyToRestartForAuth();
455 int HttpCache::Transaction::Read(IOBuffer
* buf
, int buf_len
,
456 const CompletionCallback
& callback
) {
457 DCHECK_EQ(next_state_
, STATE_NONE
);
459 DCHECK_GT(buf_len
, 0);
460 DCHECK(!callback
.is_null());
462 DCHECK(callback_
.is_null());
465 return ERR_UNEXPECTED
;
467 // If we have an intermediate auth response at this point, then it means the
468 // user wishes to read the network response (the error page). If there is a
469 // previous response in the cache then we should leave it intact.
470 if (auth_response_
.headers
.get() && mode_
!= NONE
) {
471 UpdateTransactionPattern(PATTERN_NOT_COVERED
);
472 DCHECK(mode_
& WRITE
);
473 DoneWritingToEntry(mode_
== READ_WRITE
);
479 io_buf_len_
= buf_len
;
480 if (network_trans_
) {
481 DCHECK(mode_
== WRITE
|| mode_
== NONE
||
482 (mode_
== READ_WRITE
&& partial_
));
483 next_state_
= STATE_NETWORK_READ
;
485 DCHECK(mode_
== READ
|| (mode_
== READ_WRITE
&& partial_
));
486 next_state_
= STATE_CACHE_READ_DATA
;
491 if (rv
== ERR_IO_PENDING
) {
492 DCHECK(callback_
.is_null());
493 callback_
= callback
;
498 void HttpCache::Transaction::StopCaching() {
499 // We really don't know where we are now. Hopefully there is no operation in
500 // progress, but nothing really prevents this method to be called after we
501 // returned ERR_IO_PENDING. We cannot attempt to truncate the entry at this
502 // point because we need the state machine for that (and even if we are really
503 // free, that would be an asynchronous operation). In other words, keep the
504 // entry how it is (it will be marked as truncated at destruction), and let
505 // the next piece of code that executes know that we are now reading directly
507 // TODO(mmenke): This doesn't release the lock on the cache entry, so a
508 // future request for the resource will be blocked on this one.
510 if (cache_
.get() && entry_
&& (mode_
& WRITE
) && network_trans_
.get() &&
511 !is_sparse_
&& !range_requested_
) {
516 bool HttpCache::Transaction::GetFullRequestHeaders(
517 HttpRequestHeaders
* headers
) const {
519 return network_trans_
->GetFullRequestHeaders(headers
);
521 // TODO(ttuttle): Read headers from cache.
525 int64
HttpCache::Transaction::GetTotalReceivedBytes() const {
526 int64 total_received_bytes
= total_received_bytes_
;
528 total_received_bytes
+= network_trans_
->GetTotalReceivedBytes();
529 return total_received_bytes
;
532 int64_t HttpCache::Transaction::GetTotalSentBytes() const {
533 int64_t total_sent_bytes
= total_sent_bytes_
;
535 total_sent_bytes
+= network_trans_
->GetTotalSentBytes();
536 return total_sent_bytes
;
539 void HttpCache::Transaction::DoneReading() {
540 if (cache_
.get() && entry_
) {
541 DCHECK_NE(mode_
, UPDATE
);
543 DoneWritingToEntry(true);
544 } else if (mode_
& READ
) {
545 // It is necessary to check mode_ & READ because it is possible
546 // for mode_ to be NONE and entry_ non-NULL with a write entry
547 // if StopCaching was called.
548 cache_
->DoneReadingFromEntry(entry_
, this);
554 const HttpResponseInfo
* HttpCache::Transaction::GetResponseInfo() const {
555 // Null headers means we encountered an error or haven't a response yet
556 if (auth_response_
.headers
.get())
557 return &auth_response_
;
561 LoadState
HttpCache::Transaction::GetLoadState() const {
562 LoadState state
= GetWriterLoadState();
563 if (state
!= LOAD_STATE_WAITING_FOR_CACHE
)
567 return cache_
->GetLoadStateForPendingTransaction(this);
569 return LOAD_STATE_IDLE
;
572 UploadProgress
HttpCache::Transaction::GetUploadProgress() const {
573 if (network_trans_
.get())
574 return network_trans_
->GetUploadProgress();
575 return final_upload_progress_
;
578 void HttpCache::Transaction::SetQuicServerInfo(
579 QuicServerInfo
* quic_server_info
) {}
581 bool HttpCache::Transaction::GetLoadTimingInfo(
582 LoadTimingInfo
* load_timing_info
) const {
584 return network_trans_
->GetLoadTimingInfo(load_timing_info
);
586 if (old_network_trans_load_timing_
) {
587 *load_timing_info
= *old_network_trans_load_timing_
;
591 if (first_cache_access_since_
.is_null())
594 // If the cache entry was opened, return that time.
595 load_timing_info
->send_start
= first_cache_access_since_
;
596 // This time doesn't make much sense when reading from the cache, so just use
597 // the same time as send_start.
598 load_timing_info
->send_end
= first_cache_access_since_
;
602 void HttpCache::Transaction::SetPriority(RequestPriority priority
) {
603 priority_
= priority
;
605 network_trans_
->SetPriority(priority_
);
608 void HttpCache::Transaction::SetWebSocketHandshakeStreamCreateHelper(
609 WebSocketHandshakeStreamBase::CreateHelper
* create_helper
) {
610 websocket_handshake_stream_base_create_helper_
= create_helper
;
612 network_trans_
->SetWebSocketHandshakeStreamCreateHelper(create_helper
);
615 void HttpCache::Transaction::SetBeforeNetworkStartCallback(
616 const BeforeNetworkStartCallback
& callback
) {
617 DCHECK(!network_trans_
);
618 before_network_start_callback_
= callback
;
621 void HttpCache::Transaction::SetBeforeProxyHeadersSentCallback(
622 const BeforeProxyHeadersSentCallback
& callback
) {
623 DCHECK(!network_trans_
);
624 before_proxy_headers_sent_callback_
= callback
;
627 int HttpCache::Transaction::ResumeNetworkStart() {
629 return network_trans_
->ResumeNetworkStart();
630 return ERR_UNEXPECTED
;
633 void HttpCache::Transaction::GetConnectionAttempts(
634 ConnectionAttempts
* out
) const {
635 ConnectionAttempts new_connection_attempts
;
637 network_trans_
->GetConnectionAttempts(&new_connection_attempts
);
639 out
->swap(new_connection_attempts
);
640 out
->insert(out
->begin(), old_connection_attempts_
.begin(),
641 old_connection_attempts_
.end());
644 //-----------------------------------------------------------------------------
646 // A few common patterns: (Foo* means Foo -> FooComplete)
648 // 1. Not-cached entry:
650 // GetBackend* -> InitEntry -> OpenEntry* -> CreateEntry* -> AddToEntry* ->
651 // SendRequest* -> SuccessfulSendRequest -> OverwriteCachedResponse ->
652 // CacheWriteResponse* -> TruncateCachedData* -> TruncateCachedMetadata* ->
653 // PartialHeadersReceived
656 // NetworkRead* -> CacheWriteData*
658 // 2. Cached entry, no validation:
660 // GetBackend* -> InitEntry -> OpenEntry* -> AddToEntry* -> CacheReadResponse*
661 // -> CacheDispatchValidation -> BeginPartialCacheValidation() ->
662 // BeginCacheValidation() -> SetupEntryForRead()
667 // 3. Cached entry, validation (304):
669 // GetBackend* -> InitEntry -> OpenEntry* -> AddToEntry* -> CacheReadResponse*
670 // -> CacheDispatchValidation -> BeginPartialCacheValidation() ->
671 // BeginCacheValidation() -> SendRequest* -> SuccessfulSendRequest ->
672 // UpdateCachedResponse -> CacheWriteUpdatedResponse* ->
673 // UpdateCachedResponseComplete -> OverwriteCachedResponse ->
674 // PartialHeadersReceived
679 // 4. Cached entry, validation and replace (200):
681 // GetBackend* -> InitEntry -> OpenEntry* -> AddToEntry* -> CacheReadResponse*
682 // -> CacheDispatchValidation -> BeginPartialCacheValidation() ->
683 // BeginCacheValidation() -> SendRequest* -> SuccessfulSendRequest ->
684 // OverwriteCachedResponse -> CacheWriteResponse* -> DoTruncateCachedData* ->
685 // TruncateCachedMetadata* -> PartialHeadersReceived
688 // NetworkRead* -> CacheWriteData*
690 // 5. Sparse entry, partially cached, byte range request:
692 // GetBackend* -> InitEntry -> OpenEntry* -> AddToEntry* -> CacheReadResponse*
693 // -> CacheDispatchValidation -> BeginPartialCacheValidation() ->
694 // CacheQueryData* -> ValidateEntryHeadersAndContinue() ->
695 // StartPartialCacheValidation -> CompletePartialCacheValidation ->
696 // BeginCacheValidation() -> SendRequest* -> SuccessfulSendRequest ->
697 // UpdateCachedResponse -> CacheWriteUpdatedResponse* ->
698 // UpdateCachedResponseComplete -> OverwriteCachedResponse ->
699 // PartialHeadersReceived
702 // NetworkRead* -> CacheWriteData*
705 // NetworkRead* -> CacheWriteData* -> StartPartialCacheValidation ->
706 // CompletePartialCacheValidation -> CacheReadData* ->
709 // CacheReadData* -> StartPartialCacheValidation ->
710 // CompletePartialCacheValidation -> BeginCacheValidation() -> SendRequest* ->
711 // SuccessfulSendRequest -> UpdateCachedResponse* -> OverwriteCachedResponse
712 // -> PartialHeadersReceived -> NetworkRead* -> CacheWriteData*
714 // 6. HEAD. Not-cached entry:
715 // Pass through. Don't save a HEAD by itself.
717 // GetBackend* -> InitEntry -> OpenEntry* -> SendRequest*
719 // 7. HEAD. Cached entry, no validation:
721 // The same flow as for a GET request (example #2)
724 // CacheReadData (returns 0)
726 // 8. HEAD. Cached entry, validation (304):
727 // The request updates the stored headers.
728 // Start(): Same as for a GET request (example #3)
731 // CacheReadData (returns 0)
733 // 9. HEAD. Cached entry, validation and replace (200):
734 // Pass through. The request dooms the old entry, as a HEAD won't be stored by
737 // GetBackend* -> InitEntry -> OpenEntry* -> AddToEntry* -> CacheReadResponse*
738 // -> CacheDispatchValidation -> BeginPartialCacheValidation() ->
739 // BeginCacheValidation() -> SendRequest* -> SuccessfulSendRequest ->
740 // OverwriteCachedResponse
742 // 10. HEAD. Sparse entry, partially cached:
743 // Serve the request from the cache, as long as it doesn't require
744 // revalidation. Ignore missing ranges when deciding to revalidate. If the
745 // entry requires revalidation, ignore the whole request and go to full pass
746 // through (the result of the HEAD request will NOT update the entry).
748 // Start(): Basically the same as example 7, as we never create a partial_
749 // object for this request.
751 // 11. Prefetch, not-cached entry:
752 // The same as example 1. The "unused_since_prefetch" bit is stored as true in
753 // UpdateCachedResponse.
755 // 12. Prefetch, cached entry:
756 // Like examples 2-4, only CacheToggleUnusedSincePrefetch* is inserted between
757 // CacheReadResponse* and CacheDispatchValidation if the unused_since_prefetch
760 // 13. Cached entry less than 5 minutes old, unused_since_prefetch is true:
761 // Skip validation, similar to example 2.
762 // GetBackend* -> InitEntry -> OpenEntry* -> AddToEntry* -> CacheReadResponse*
763 // -> CacheToggleUnusedSincePrefetch* -> CacheDispatchValidation ->
764 // BeginPartialCacheValidation() -> BeginCacheValidation() ->
765 // SetupEntryForRead()
770 // 14. Cached entry more than 5 minutes old, unused_since_prefetch is true:
771 // Like examples 2-4, only CacheToggleUnusedSincePrefetch* is inserted between
772 // CacheReadResponse* and CacheDispatchValidation.
773 int HttpCache::Transaction::DoLoop(int result
) {
774 DCHECK(next_state_
!= STATE_NONE
);
778 State state
= next_state_
;
779 next_state_
= STATE_NONE
;
781 case STATE_GET_BACKEND
:
785 case STATE_GET_BACKEND_COMPLETE
:
786 rv
= DoGetBackendComplete(rv
);
788 case STATE_INIT_ENTRY
:
792 case STATE_OPEN_ENTRY
:
796 case STATE_OPEN_ENTRY_COMPLETE
:
797 rv
= DoOpenEntryComplete(rv
);
799 case STATE_DOOM_ENTRY
:
803 case STATE_DOOM_ENTRY_COMPLETE
:
804 rv
= DoDoomEntryComplete(rv
);
806 case STATE_CREATE_ENTRY
:
808 rv
= DoCreateEntry();
810 case STATE_CREATE_ENTRY_COMPLETE
:
811 rv
= DoCreateEntryComplete(rv
);
813 case STATE_ADD_TO_ENTRY
:
817 case STATE_ADD_TO_ENTRY_COMPLETE
:
818 rv
= DoAddToEntryComplete(rv
);
820 case STATE_CACHE_READ_RESPONSE
:
822 rv
= DoCacheReadResponse();
824 case STATE_CACHE_READ_RESPONSE_COMPLETE
:
825 rv
= DoCacheReadResponseComplete(rv
);
827 case STATE_TOGGLE_UNUSED_SINCE_PREFETCH
:
829 rv
= DoCacheToggleUnusedSincePrefetch();
831 case STATE_TOGGLE_UNUSED_SINCE_PREFETCH_COMPLETE
:
832 rv
= DoCacheToggleUnusedSincePrefetchComplete(rv
);
834 case STATE_CACHE_DISPATCH_VALIDATION
:
836 rv
= DoCacheDispatchValidation();
838 case STATE_CACHE_QUERY_DATA
:
840 rv
= DoCacheQueryData();
842 case STATE_CACHE_QUERY_DATA_COMPLETE
:
843 rv
= DoCacheQueryDataComplete(rv
);
845 case STATE_START_PARTIAL_CACHE_VALIDATION
:
847 rv
= DoStartPartialCacheValidation();
849 case STATE_COMPLETE_PARTIAL_CACHE_VALIDATION
:
850 rv
= DoCompletePartialCacheValidation(rv
);
852 case STATE_SEND_REQUEST
:
854 rv
= DoSendRequest();
856 case STATE_SEND_REQUEST_COMPLETE
:
857 rv
= DoSendRequestComplete(rv
);
859 case STATE_SUCCESSFUL_SEND_REQUEST
:
861 rv
= DoSuccessfulSendRequest();
863 case STATE_UPDATE_CACHED_RESPONSE
:
865 rv
= DoUpdateCachedResponse();
867 case STATE_CACHE_WRITE_UPDATED_RESPONSE
:
869 rv
= DoCacheWriteUpdatedResponse();
871 case STATE_CACHE_WRITE_UPDATED_RESPONSE_COMPLETE
:
872 rv
= DoCacheWriteUpdatedResponseComplete(rv
);
874 case STATE_UPDATE_CACHED_RESPONSE_COMPLETE
:
875 rv
= DoUpdateCachedResponseComplete(rv
);
877 case STATE_OVERWRITE_CACHED_RESPONSE
:
879 rv
= DoOverwriteCachedResponse();
881 case STATE_CACHE_WRITE_RESPONSE
:
883 rv
= DoCacheWriteResponse();
885 case STATE_CACHE_WRITE_RESPONSE_COMPLETE
:
886 rv
= DoCacheWriteResponseComplete(rv
);
888 case STATE_TRUNCATE_CACHED_DATA
:
890 rv
= DoTruncateCachedData();
892 case STATE_TRUNCATE_CACHED_DATA_COMPLETE
:
893 rv
= DoTruncateCachedDataComplete(rv
);
895 case STATE_TRUNCATE_CACHED_METADATA
:
897 rv
= DoTruncateCachedMetadata();
899 case STATE_TRUNCATE_CACHED_METADATA_COMPLETE
:
900 rv
= DoTruncateCachedMetadataComplete(rv
);
902 case STATE_PARTIAL_HEADERS_RECEIVED
:
904 rv
= DoPartialHeadersReceived();
906 case STATE_CACHE_READ_METADATA
:
908 rv
= DoCacheReadMetadata();
910 case STATE_CACHE_READ_METADATA_COMPLETE
:
911 rv
= DoCacheReadMetadataComplete(rv
);
913 case STATE_NETWORK_READ
:
915 rv
= DoNetworkRead();
917 case STATE_NETWORK_READ_COMPLETE
:
918 rv
= DoNetworkReadComplete(rv
);
920 case STATE_CACHE_READ_DATA
:
922 rv
= DoCacheReadData();
924 case STATE_CACHE_READ_DATA_COMPLETE
:
925 rv
= DoCacheReadDataComplete(rv
);
927 case STATE_CACHE_WRITE_DATA
:
928 rv
= DoCacheWriteData(rv
);
930 case STATE_CACHE_WRITE_DATA_COMPLETE
:
931 rv
= DoCacheWriteDataComplete(rv
);
933 case STATE_CACHE_WRITE_TRUNCATED_RESPONSE
:
935 rv
= DoCacheWriteTruncatedResponse();
937 case STATE_CACHE_WRITE_TRUNCATED_RESPONSE_COMPLETE
:
938 rv
= DoCacheWriteTruncatedResponseComplete(rv
);
941 NOTREACHED() << "bad state";
945 } while (rv
!= ERR_IO_PENDING
&& next_state_
!= STATE_NONE
);
947 if (rv
!= ERR_IO_PENDING
&& !callback_
.is_null()) {
948 read_buf_
= NULL
; // Release the buffer before invoking the callback.
949 base::ResetAndReturn(&callback_
).Run(rv
);
955 int HttpCache::Transaction::DoGetBackend() {
956 cache_pending_
= true;
957 next_state_
= STATE_GET_BACKEND_COMPLETE
;
958 net_log_
.BeginEvent(NetLog::TYPE_HTTP_CACHE_GET_BACKEND
);
959 return cache_
->GetBackendForTransaction(this);
962 int HttpCache::Transaction::DoGetBackendComplete(int result
) {
963 DCHECK(result
== OK
|| result
== ERR_FAILED
);
964 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_HTTP_CACHE_GET_BACKEND
,
966 cache_pending_
= false;
968 if (!ShouldPassThrough()) {
969 cache_key_
= cache_
->GenerateCacheKey(request_
);
971 // Requested cache access mode.
972 if (effective_load_flags_
& LOAD_ONLY_FROM_CACHE
) {
974 } else if (effective_load_flags_
& LOAD_BYPASS_CACHE
) {
980 // Downgrade to UPDATE if the request has been externally conditionalized.
981 if (external_validation_
.initialized
) {
983 // Strip off the READ_DATA bit (and maybe add back a READ_META bit
984 // in case READ was off).
992 // Use PUT and DELETE only to invalidate existing stored entries.
993 if ((request_
->method
== "PUT" || request_
->method
== "DELETE") &&
994 mode_
!= READ_WRITE
&& mode_
!= WRITE
) {
998 // Note that if mode_ == UPDATE (which is tied to external_validation_), the
999 // transaction behaves the same for GET and HEAD requests at this point: if it
1000 // was not modified, the entry is updated and a response is not returned from
1001 // the cache. If we receive 200, it doesn't matter if there was a validation
1003 if (request_
->method
== "HEAD" && mode_
== WRITE
)
1006 // If must use cache, then we must fail. This can happen for back/forward
1007 // navigations to a page generated via a form post.
1008 if (!(mode_
& READ
) && effective_load_flags_
& LOAD_ONLY_FROM_CACHE
)
1009 return ERR_CACHE_MISS
;
1011 if (mode_
== NONE
) {
1013 partial_
->RestoreHeaders(&custom_request_
->extra_headers
);
1016 next_state_
= STATE_SEND_REQUEST
;
1018 next_state_
= STATE_INIT_ENTRY
;
1021 // This is only set if we have something to do with the response.
1022 range_requested_
= (partial_
.get() != NULL
);
1027 int HttpCache::Transaction::DoInitEntry() {
1028 DCHECK(!new_entry_
);
1031 return ERR_UNEXPECTED
;
1033 if (mode_
== WRITE
) {
1034 next_state_
= STATE_DOOM_ENTRY
;
1038 next_state_
= STATE_OPEN_ENTRY
;
1042 int HttpCache::Transaction::DoOpenEntry() {
1043 DCHECK(!new_entry_
);
1044 next_state_
= STATE_OPEN_ENTRY_COMPLETE
;
1045 cache_pending_
= true;
1046 net_log_
.BeginEvent(NetLog::TYPE_HTTP_CACHE_OPEN_ENTRY
);
1047 first_cache_access_since_
= TimeTicks::Now();
1048 return cache_
->OpenEntry(cache_key_
, &new_entry_
, this);
1051 int HttpCache::Transaction::DoOpenEntryComplete(int result
) {
1052 // It is important that we go to STATE_ADD_TO_ENTRY whenever the result is
1053 // OK, otherwise the cache will end up with an active entry without any
1054 // transaction attached.
1055 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_HTTP_CACHE_OPEN_ENTRY
, result
);
1056 cache_pending_
= false;
1058 next_state_
= STATE_ADD_TO_ENTRY
;
1062 if (result
== ERR_CACHE_RACE
) {
1063 next_state_
= STATE_INIT_ENTRY
;
1067 if (request_
->method
== "PUT" || request_
->method
== "DELETE" ||
1068 (request_
->method
== "HEAD" && mode_
== READ_WRITE
)) {
1069 DCHECK(mode_
== READ_WRITE
|| mode_
== WRITE
|| request_
->method
== "HEAD");
1071 next_state_
= STATE_SEND_REQUEST
;
1075 if (mode_
== READ_WRITE
) {
1077 next_state_
= STATE_CREATE_ENTRY
;
1080 if (mode_
== UPDATE
) {
1081 // There is no cache entry to update; proceed without caching.
1083 next_state_
= STATE_SEND_REQUEST
;
1087 // The entry does not exist, and we are not permitted to create a new entry,
1089 return ERR_CACHE_MISS
;
1092 int HttpCache::Transaction::DoDoomEntry() {
1093 next_state_
= STATE_DOOM_ENTRY_COMPLETE
;
1094 cache_pending_
= true;
1095 if (first_cache_access_since_
.is_null())
1096 first_cache_access_since_
= TimeTicks::Now();
1097 net_log_
.BeginEvent(NetLog::TYPE_HTTP_CACHE_DOOM_ENTRY
);
1098 return cache_
->DoomEntry(cache_key_
, this);
1101 int HttpCache::Transaction::DoDoomEntryComplete(int result
) {
1102 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_HTTP_CACHE_DOOM_ENTRY
, result
);
1103 next_state_
= STATE_CREATE_ENTRY
;
1104 cache_pending_
= false;
1105 if (result
== ERR_CACHE_RACE
)
1106 next_state_
= STATE_INIT_ENTRY
;
1110 int HttpCache::Transaction::DoCreateEntry() {
1111 DCHECK(!new_entry_
);
1112 next_state_
= STATE_CREATE_ENTRY_COMPLETE
;
1113 cache_pending_
= true;
1114 net_log_
.BeginEvent(NetLog::TYPE_HTTP_CACHE_CREATE_ENTRY
);
1115 return cache_
->CreateEntry(cache_key_
, &new_entry_
, this);
1118 int HttpCache::Transaction::DoCreateEntryComplete(int result
) {
1119 // It is important that we go to STATE_ADD_TO_ENTRY whenever the result is
1120 // OK, otherwise the cache will end up with an active entry without any
1121 // transaction attached.
1122 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_HTTP_CACHE_CREATE_ENTRY
,
1124 cache_pending_
= false;
1127 next_state_
= STATE_ADD_TO_ENTRY
;
1130 case ERR_CACHE_RACE
:
1131 next_state_
= STATE_INIT_ENTRY
;
1135 // We have a race here: Maybe we failed to open the entry and decided to
1136 // create one, but by the time we called create, another transaction
1137 // already created the entry. If we want to eliminate this issue, we
1138 // need an atomic OpenOrCreate() method exposed by the disk cache.
1139 DLOG(WARNING
) << "Unable to create cache entry";
1142 partial_
->RestoreHeaders(&custom_request_
->extra_headers
);
1143 next_state_
= STATE_SEND_REQUEST
;
1148 int HttpCache::Transaction::DoAddToEntry() {
1150 cache_pending_
= true;
1151 next_state_
= STATE_ADD_TO_ENTRY_COMPLETE
;
1152 net_log_
.BeginEvent(NetLog::TYPE_HTTP_CACHE_ADD_TO_ENTRY
);
1153 DCHECK(entry_lock_waiting_since_
.is_null());
1154 entry_lock_waiting_since_
= TimeTicks::Now();
1155 int rv
= cache_
->AddTransactionToEntry(new_entry_
, this);
1156 if (rv
== ERR_IO_PENDING
) {
1157 if (bypass_lock_for_test_
) {
1158 OnAddToEntryTimeout(entry_lock_waiting_since_
);
1160 int timeout_milliseconds
= 20 * 1000;
1161 if (partial_
&& new_entry_
->writer
&&
1162 new_entry_
->writer
->range_requested_
) {
1163 // Quickly timeout and bypass the cache if we're a range request and
1164 // we're blocked by the reader/writer lock. Doing so eliminates a long
1165 // running issue, http://crbug.com/31014, where two of the same media
1166 // resources could not be played back simultaneously due to one locking
1167 // the cache entry until the entire video was downloaded.
1169 // Bypassing the cache is not ideal, as we are now ignoring the cache
1170 // entirely for all range requests to a resource beyond the first. This
1171 // is however a much more succinct solution than the alternatives, which
1172 // would require somewhat significant changes to the http caching logic.
1174 // Allow some timeout slack for the entry addition to complete in case
1175 // the writer lock is imminently released; we want to avoid skipping
1176 // the cache if at all possible. See http://crbug.com/408765
1177 timeout_milliseconds
= 25;
1179 base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
1181 base::Bind(&HttpCache::Transaction::OnAddToEntryTimeout
,
1182 weak_factory_
.GetWeakPtr(), entry_lock_waiting_since_
),
1183 TimeDelta::FromMilliseconds(timeout_milliseconds
));
1189 int HttpCache::Transaction::DoAddToEntryComplete(int result
) {
1190 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_HTTP_CACHE_ADD_TO_ENTRY
,
1192 const TimeDelta entry_lock_wait
=
1193 TimeTicks::Now() - entry_lock_waiting_since_
;
1194 UMA_HISTOGRAM_TIMES("HttpCache.EntryLockWait", entry_lock_wait
);
1196 entry_lock_waiting_since_
= TimeTicks();
1198 cache_pending_
= false;
1201 entry_
= new_entry_
;
1203 // If there is a failure, the cache should have taken care of new_entry_.
1206 if (result
== ERR_CACHE_RACE
) {
1207 next_state_
= STATE_INIT_ENTRY
;
1211 if (result
== ERR_CACHE_LOCK_TIMEOUT
) {
1212 // The cache is busy, bypass it for this transaction.
1214 next_state_
= STATE_SEND_REQUEST
;
1216 partial_
->RestoreHeaders(&custom_request_
->extra_headers
);
1227 if (mode_
== WRITE
) {
1229 partial_
->RestoreHeaders(&custom_request_
->extra_headers
);
1230 next_state_
= STATE_SEND_REQUEST
;
1232 // We have to read the headers from the cached entry.
1233 DCHECK(mode_
& READ_META
);
1234 next_state_
= STATE_CACHE_READ_RESPONSE
;
1239 int HttpCache::Transaction::DoCacheReadResponse() {
1241 next_state_
= STATE_CACHE_READ_RESPONSE_COMPLETE
;
1243 io_buf_len_
= entry_
->disk_entry
->GetDataSize(kResponseInfoIndex
);
1244 read_buf_
= new IOBuffer(io_buf_len_
);
1246 net_log_
.BeginEvent(NetLog::TYPE_HTTP_CACHE_READ_INFO
);
1247 return entry_
->disk_entry
->ReadData(kResponseInfoIndex
, 0, read_buf_
.get(),
1248 io_buf_len_
, io_callback_
);
1251 int HttpCache::Transaction::DoCacheReadResponseComplete(int result
) {
1252 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_HTTP_CACHE_READ_INFO
, result
);
1253 if (result
!= io_buf_len_
||
1254 !HttpCache::ParseResponseInfo(read_buf_
->data(), io_buf_len_
, &response_
,
1256 return OnCacheReadError(result
, true);
1259 // cert_cache() will be null if the CertCacheTrial field trial is disabled.
1260 if (cache_
->cert_cache() && response_
.ssl_info
.is_valid())
1263 // Some resources may have slipped in as truncated when they're not.
1264 int current_size
= entry_
->disk_entry
->GetDataSize(kResponseContentIndex
);
1265 if (response_
.headers
->GetContentLength() == current_size
)
1268 if ((response_
.unused_since_prefetch
&&
1269 !(request_
->load_flags
& LOAD_PREFETCH
)) ||
1270 (!response_
.unused_since_prefetch
&&
1271 (request_
->load_flags
& LOAD_PREFETCH
))) {
1272 // Either this is the first use of an entry since it was prefetched or
1273 // this is a prefetch. The value of response.unused_since_prefetch is valid
1274 // for this transaction but the bit needs to be flipped in storage.
1275 next_state_
= STATE_TOGGLE_UNUSED_SINCE_PREFETCH
;
1279 next_state_
= STATE_CACHE_DISPATCH_VALIDATION
;
1283 int HttpCache::Transaction::DoCacheToggleUnusedSincePrefetch() {
1284 // Write back the toggled value for the next use of this entry.
1285 response_
.unused_since_prefetch
= !response_
.unused_since_prefetch
;
1287 // TODO(jkarlin): If DoUpdateCachedResponse is also called for this
1288 // transaction then metadata will be written to cache twice. If prefetching
1289 // becomes more common, consider combining the writes.
1291 // TODO(rtenneti): Remove ScopedTracker below once crbug.com/422516 is fixed.
1292 tracked_objects::ScopedTracker
tracking_profile(
1293 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1294 "422516 HttpCache::Transaction::DoCacheToggleUnusedSincePrefetch"));
1296 next_state_
= STATE_TOGGLE_UNUSED_SINCE_PREFETCH_COMPLETE
;
1297 return WriteResponseInfoToEntry(false);
1300 int HttpCache::Transaction::DoCacheToggleUnusedSincePrefetchComplete(
1302 // Restore the original value for this transaction.
1303 response_
.unused_since_prefetch
= !response_
.unused_since_prefetch
;
1304 next_state_
= STATE_CACHE_DISPATCH_VALIDATION
;
1305 return OnWriteResponseInfoToEntryComplete(result
);
1308 int HttpCache::Transaction::DoCacheDispatchValidation() {
1309 // We now have access to the cache entry.
1311 // o if we are a reader for the transaction, then we can start reading the
1314 // o if we can read or write, then we should check if the cache entry needs
1315 // to be validated and then issue a network request if needed or just read
1316 // from the cache if the cache entry is already valid.
1318 // o if we are set to UPDATE, then we are handling an externally
1319 // conditionalized request (if-modified-since / if-none-match). We check
1320 // if the request headers define a validation request.
1322 int result
= ERR_FAILED
;
1325 UpdateTransactionPattern(PATTERN_ENTRY_USED
);
1326 result
= BeginCacheRead();
1329 result
= BeginPartialCacheValidation();
1332 result
= BeginExternallyConditionalizedRequest();
1341 int HttpCache::Transaction::DoCacheQueryData() {
1342 next_state_
= STATE_CACHE_QUERY_DATA_COMPLETE
;
1343 return entry_
->disk_entry
->ReadyForSparseIO(io_callback_
);
1346 int HttpCache::Transaction::DoCacheQueryDataComplete(int result
) {
1347 DCHECK_EQ(OK
, result
);
1349 return ERR_UNEXPECTED
;
1351 return ValidateEntryHeadersAndContinue();
1354 // We may end up here multiple times for a given request.
1355 int HttpCache::Transaction::DoStartPartialCacheValidation() {
1359 next_state_
= STATE_COMPLETE_PARTIAL_CACHE_VALIDATION
;
1360 return partial_
->ShouldValidateCache(entry_
->disk_entry
, io_callback_
);
1363 int HttpCache::Transaction::DoCompletePartialCacheValidation(int result
) {
1365 // This is the end of the request.
1366 if (mode_
& WRITE
) {
1367 DoneWritingToEntry(true);
1369 cache_
->DoneReadingFromEntry(entry_
, this);
1378 partial_
->PrepareCacheValidation(entry_
->disk_entry
,
1379 &custom_request_
->extra_headers
);
1381 if (reading_
&& partial_
->IsCurrentRangeCached()) {
1382 next_state_
= STATE_CACHE_READ_DATA
;
1386 return BeginCacheValidation();
1389 int HttpCache::Transaction::DoSendRequest() {
1390 DCHECK(mode_
& WRITE
|| mode_
== NONE
);
1391 DCHECK(!network_trans_
.get());
1393 send_request_since_
= TimeTicks::Now();
1395 // Create a network transaction.
1397 cache_
->network_layer_
->CreateTransaction(priority_
, &network_trans_
);
1400 network_trans_
->SetBeforeNetworkStartCallback(before_network_start_callback_
);
1401 network_trans_
->SetBeforeProxyHeadersSentCallback(
1402 before_proxy_headers_sent_callback_
);
1404 // Old load timing information, if any, is now obsolete.
1405 old_network_trans_load_timing_
.reset();
1407 if (websocket_handshake_stream_base_create_helper_
)
1408 network_trans_
->SetWebSocketHandshakeStreamCreateHelper(
1409 websocket_handshake_stream_base_create_helper_
);
1411 next_state_
= STATE_SEND_REQUEST_COMPLETE
;
1412 rv
= network_trans_
->Start(request_
, io_callback_
, net_log_
);
1416 int HttpCache::Transaction::DoSendRequestComplete(int result
) {
1418 return ERR_UNEXPECTED
;
1420 // If we tried to conditionalize the request and failed, we know
1421 // we won't be reading from the cache after this point.
1422 if (couldnt_conditionalize_request_
)
1426 next_state_
= STATE_SUCCESSFUL_SEND_REQUEST
;
1430 const HttpResponseInfo
* response
= network_trans_
->GetResponseInfo();
1431 response_
.network_accessed
= response
->network_accessed
;
1433 // Do not record requests that have network errors or restarts.
1434 UpdateTransactionPattern(PATTERN_NOT_COVERED
);
1435 if (IsCertificateError(result
)) {
1436 // If we get a certificate error, then there is a certificate in ssl_info,
1437 // so GetResponseInfo() should never return NULL here.
1439 response_
.ssl_info
= response
->ssl_info
;
1440 } else if (result
== ERR_SSL_CLIENT_AUTH_CERT_NEEDED
) {
1442 response_
.cert_request_info
= response
->cert_request_info
;
1443 } else if (response_
.was_cached
) {
1444 DoneWritingToEntry(true);
1450 // We received the response headers and there is no error.
1451 int HttpCache::Transaction::DoSuccessfulSendRequest() {
1452 DCHECK(!new_response_
);
1453 const HttpResponseInfo
* new_response
= network_trans_
->GetResponseInfo();
1455 if (new_response
->headers
->response_code() == 401 ||
1456 new_response
->headers
->response_code() == 407) {
1457 auth_response_
= *new_response
;
1461 // We initiated a second request the caller doesn't know about. We should be
1462 // able to authenticate this request because we should have authenticated
1463 // this URL moments ago.
1464 if (IsReadyToRestartForAuth()) {
1465 DCHECK(!response_
.auth_challenge
.get());
1466 next_state_
= STATE_SEND_REQUEST_COMPLETE
;
1467 // In theory we should check to see if there are new cookies, but there
1468 // is no way to do that from here.
1469 return network_trans_
->RestartWithAuth(AuthCredentials(), io_callback_
);
1472 // We have to perform cleanup at this point so that at least the next
1473 // request can succeed. We do not retry at this point, because data
1474 // has been read and we have no way to gather credentials. We would
1475 // fail again, and potentially loop. This can happen if the credentials
1476 // expire while chrome is suspended.
1478 DoomPartialEntry(false);
1481 ResetNetworkTransaction();
1482 return ERR_CACHE_AUTH_FAILURE_AFTER_READ
;
1485 new_response_
= new_response
;
1486 if (!ValidatePartialResponse() && !auth_response_
.headers
.get()) {
1487 // Something went wrong with this request and we have to restart it.
1488 // If we have an authentication response, we are exposed to weird things
1489 // hapenning if the user cancels the authentication before we receive
1490 // the new response.
1491 net_log_
.AddEvent(NetLog::TYPE_HTTP_CACHE_RE_SEND_PARTIAL_REQUEST
);
1492 UpdateTransactionPattern(PATTERN_NOT_COVERED
);
1493 response_
= HttpResponseInfo();
1494 ResetNetworkTransaction();
1495 new_response_
= NULL
;
1496 next_state_
= STATE_SEND_REQUEST
;
1500 if (handling_206_
&& mode_
== READ_WRITE
&& !truncated_
&& !is_sparse_
) {
1501 // We have stored the full entry, but it changed and the server is
1502 // sending a range. We have to delete the old entry.
1503 UpdateTransactionPattern(PATTERN_NOT_COVERED
);
1504 DoneWritingToEntry(false);
1507 if (mode_
== WRITE
&&
1508 transaction_pattern_
!= PATTERN_ENTRY_CANT_CONDITIONALIZE
) {
1509 UpdateTransactionPattern(PATTERN_ENTRY_NOT_CACHED
);
1512 // Invalidate any cached GET with a successful PUT or DELETE.
1513 if (mode_
== WRITE
&&
1514 (request_
->method
== "PUT" || request_
->method
== "DELETE")) {
1515 if (NonErrorResponse(new_response
->headers
->response_code())) {
1516 int ret
= cache_
->DoomEntry(cache_key_
, NULL
);
1519 cache_
->DoneWritingToEntry(entry_
, true);
1524 // Invalidate any cached GET with a successful POST.
1525 if (!(effective_load_flags_
& LOAD_DISABLE_CACHE
) &&
1526 request_
->method
== "POST" &&
1527 NonErrorResponse(new_response
->headers
->response_code())) {
1528 cache_
->DoomMainEntryForUrl(request_
->url
);
1531 RecordNoStoreHeaderHistogram(request_
->load_flags
, new_response
);
1533 if (new_response_
->headers
->response_code() == 416 &&
1534 (request_
->method
== "GET" || request_
->method
== "POST")) {
1535 // If there is an active entry it may be destroyed with this transaction.
1536 response_
= *new_response_
;
1540 // Are we expecting a response to a conditional query?
1541 if (mode_
== READ_WRITE
|| mode_
== UPDATE
) {
1542 if (new_response
->headers
->response_code() == 304 || handling_206_
) {
1543 UpdateTransactionPattern(PATTERN_ENTRY_VALIDATED
);
1544 next_state_
= STATE_UPDATE_CACHED_RESPONSE
;
1547 UpdateTransactionPattern(PATTERN_ENTRY_UPDATED
);
1551 next_state_
= STATE_OVERWRITE_CACHED_RESPONSE
;
1555 // We received 304 or 206 and we want to update the cached response headers.
1556 int HttpCache::Transaction::DoUpdateCachedResponse() {
1557 next_state_
= STATE_UPDATE_CACHED_RESPONSE_COMPLETE
;
1559 // Update the cached response based on the headers and properties of
1561 response_
.headers
->Update(*new_response_
->headers
.get());
1562 response_
.response_time
= new_response_
->response_time
;
1563 response_
.request_time
= new_response_
->request_time
;
1564 response_
.network_accessed
= new_response_
->network_accessed
;
1565 response_
.unused_since_prefetch
= new_response_
->unused_since_prefetch
;
1566 response_
.ssl_info
= new_response_
->ssl_info
;
1567 if (new_response_
->vary_data
.is_valid()) {
1568 response_
.vary_data
= new_response_
->vary_data
;
1569 } else if (response_
.vary_data
.is_valid()) {
1570 // There is a vary header in the stored response but not in the current one.
1571 // Update the data with the new request headers.
1572 HttpVaryData new_vary_data
;
1573 new_vary_data
.Init(*request_
, *response_
.headers
.get());
1574 response_
.vary_data
= new_vary_data
;
1577 if (response_
.headers
->HasHeaderValue("cache-control", "no-store")) {
1578 if (!entry_
->doomed
) {
1579 int ret
= cache_
->DoomEntry(cache_key_
, NULL
);
1583 // If we are already reading, we already updated the headers for this
1584 // request; doing it again will change Content-Length.
1586 next_state_
= STATE_CACHE_WRITE_UPDATED_RESPONSE
;
1593 int HttpCache::Transaction::DoCacheWriteUpdatedResponse() {
1594 // TODO(rtenneti): Remove ScopedTracker below once crbug.com/422516 is fixed.
1595 tracked_objects::ScopedTracker
tracking_profile(
1596 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1597 "422516 HttpCache::Transaction::DoCacheWriteUpdatedResponse"));
1599 next_state_
= STATE_CACHE_WRITE_UPDATED_RESPONSE_COMPLETE
;
1600 return WriteResponseInfoToEntry(false);
1603 int HttpCache::Transaction::DoCacheWriteUpdatedResponseComplete(int result
) {
1604 next_state_
= STATE_UPDATE_CACHED_RESPONSE_COMPLETE
;
1605 return OnWriteResponseInfoToEntryComplete(result
);
1608 int HttpCache::Transaction::DoUpdateCachedResponseComplete(int result
) {
1609 if (mode_
== UPDATE
) {
1610 DCHECK(!handling_206_
);
1611 // We got a "not modified" response and already updated the corresponding
1612 // cache entry above.
1614 // By closing the cached entry now, we make sure that the 304 rather than
1615 // the cached 200 response, is what will be returned to the user.
1616 DoneWritingToEntry(true);
1617 } else if (entry_
&& !handling_206_
) {
1618 DCHECK_EQ(READ_WRITE
, mode_
);
1619 if (!partial_
|| partial_
->IsLastRange()) {
1620 cache_
->ConvertWriterToReader(entry_
);
1623 // We no longer need the network transaction, so destroy it.
1624 final_upload_progress_
= network_trans_
->GetUploadProgress();
1625 ResetNetworkTransaction();
1626 } else if (entry_
&& handling_206_
&& truncated_
&&
1627 partial_
->initial_validation()) {
1628 // We just finished the validation of a truncated entry, and the server
1629 // is willing to resume the operation. Now we go back and start serving
1630 // the first part to the user.
1631 ResetNetworkTransaction();
1632 new_response_
= NULL
;
1633 next_state_
= STATE_START_PARTIAL_CACHE_VALIDATION
;
1634 partial_
->SetRangeToStartDownload();
1637 next_state_
= STATE_OVERWRITE_CACHED_RESPONSE
;
1641 int HttpCache::Transaction::DoOverwriteCachedResponse() {
1643 next_state_
= STATE_PARTIAL_HEADERS_RECEIVED
;
1647 // We change the value of Content-Length for partial content.
1648 if (handling_206_
&& partial_
)
1649 partial_
->FixContentLength(new_response_
->headers
.get());
1651 response_
= *new_response_
;
1653 if (request_
->method
== "HEAD") {
1654 // This response is replacing the cached one.
1655 DoneWritingToEntry(false);
1657 new_response_
= NULL
;
1661 if (handling_206_
&& !CanResume(false)) {
1662 // There is no point in storing this resource because it will never be used.
1663 // This may change if we support LOAD_ONLY_FROM_CACHE with sparse entries.
1664 DoneWritingToEntry(false);
1666 partial_
->FixResponseHeaders(response_
.headers
.get(), true);
1667 next_state_
= STATE_PARTIAL_HEADERS_RECEIVED
;
1671 next_state_
= STATE_CACHE_WRITE_RESPONSE
;
1675 int HttpCache::Transaction::DoCacheWriteResponse() {
1676 // TODO(rtenneti): Remove ScopedTracker below once crbug.com/422516 is fixed.
1677 tracked_objects::ScopedTracker
tracking_profile(
1678 FROM_HERE_WITH_EXPLICIT_FUNCTION(
1679 "422516 HttpCache::Transaction::DoCacheWriteResponse"));
1681 next_state_
= STATE_CACHE_WRITE_RESPONSE_COMPLETE
;
1682 return WriteResponseInfoToEntry(truncated_
);
1685 int HttpCache::Transaction::DoCacheWriteResponseComplete(int result
) {
1686 next_state_
= STATE_TRUNCATE_CACHED_DATA
;
1687 return OnWriteResponseInfoToEntryComplete(result
);
1690 int HttpCache::Transaction::DoTruncateCachedData() {
1691 next_state_
= STATE_TRUNCATE_CACHED_DATA_COMPLETE
;
1694 if (net_log_
.IsCapturing())
1695 net_log_
.BeginEvent(NetLog::TYPE_HTTP_CACHE_WRITE_DATA
);
1696 // Truncate the stream.
1697 return WriteToEntry(kResponseContentIndex
, 0, NULL
, 0, io_callback_
);
1700 int HttpCache::Transaction::DoTruncateCachedDataComplete(int result
) {
1702 if (net_log_
.IsCapturing()) {
1703 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_HTTP_CACHE_WRITE_DATA
,
1708 next_state_
= STATE_TRUNCATE_CACHED_METADATA
;
1712 int HttpCache::Transaction::DoTruncateCachedMetadata() {
1713 next_state_
= STATE_TRUNCATE_CACHED_METADATA_COMPLETE
;
1717 if (net_log_
.IsCapturing())
1718 net_log_
.BeginEvent(NetLog::TYPE_HTTP_CACHE_WRITE_INFO
);
1719 return WriteToEntry(kMetadataIndex
, 0, NULL
, 0, io_callback_
);
1722 int HttpCache::Transaction::DoTruncateCachedMetadataComplete(int result
) {
1724 if (net_log_
.IsCapturing()) {
1725 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_HTTP_CACHE_WRITE_INFO
,
1730 next_state_
= STATE_PARTIAL_HEADERS_RECEIVED
;
1734 int HttpCache::Transaction::DoPartialHeadersReceived() {
1735 new_response_
= NULL
;
1736 if (entry_
&& !partial_
&& entry_
->disk_entry
->GetDataSize(kMetadataIndex
))
1737 next_state_
= STATE_CACHE_READ_METADATA
;
1743 if (network_trans_
.get()) {
1744 next_state_
= STATE_NETWORK_READ
;
1746 next_state_
= STATE_CACHE_READ_DATA
;
1748 } else if (mode_
!= NONE
) {
1749 // We are about to return the headers for a byte-range request to the user,
1750 // so let's fix them.
1751 partial_
->FixResponseHeaders(response_
.headers
.get(), true);
1756 int HttpCache::Transaction::DoCacheReadMetadata() {
1758 DCHECK(!response_
.metadata
.get());
1759 next_state_
= STATE_CACHE_READ_METADATA_COMPLETE
;
1761 response_
.metadata
=
1762 new IOBufferWithSize(entry_
->disk_entry
->GetDataSize(kMetadataIndex
));
1764 net_log_
.BeginEvent(NetLog::TYPE_HTTP_CACHE_READ_INFO
);
1765 return entry_
->disk_entry
->ReadData(kMetadataIndex
, 0,
1766 response_
.metadata
.get(),
1767 response_
.metadata
->size(),
1771 int HttpCache::Transaction::DoCacheReadMetadataComplete(int result
) {
1772 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_HTTP_CACHE_READ_INFO
, result
);
1773 if (result
!= response_
.metadata
->size())
1774 return OnCacheReadError(result
, false);
1778 int HttpCache::Transaction::DoNetworkRead() {
1779 next_state_
= STATE_NETWORK_READ_COMPLETE
;
1780 return network_trans_
->Read(read_buf_
.get(), io_buf_len_
, io_callback_
);
1783 int HttpCache::Transaction::DoNetworkReadComplete(int result
) {
1784 DCHECK(mode_
& WRITE
|| mode_
== NONE
);
1787 return ERR_UNEXPECTED
;
1789 // If there is an error or we aren't saving the data, we are done; just wait
1790 // until the destructor runs to see if we can keep the data.
1791 if (mode_
== NONE
|| result
< 0)
1794 next_state_
= STATE_CACHE_WRITE_DATA
;
1798 int HttpCache::Transaction::DoCacheReadData() {
1799 if (request_
->method
== "HEAD")
1803 next_state_
= STATE_CACHE_READ_DATA_COMPLETE
;
1805 if (net_log_
.IsCapturing())
1806 net_log_
.BeginEvent(NetLog::TYPE_HTTP_CACHE_READ_DATA
);
1808 return partial_
->CacheRead(entry_
->disk_entry
, read_buf_
.get(), io_buf_len_
,
1812 return entry_
->disk_entry
->ReadData(kResponseContentIndex
, read_offset_
,
1813 read_buf_
.get(), io_buf_len_
,
1817 int HttpCache::Transaction::DoCacheReadDataComplete(int result
) {
1818 if (net_log_
.IsCapturing()) {
1819 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_HTTP_CACHE_READ_DATA
,
1824 return ERR_UNEXPECTED
;
1827 // Partial requests are confusing to report in histograms because they may
1828 // have multiple underlying requests.
1829 UpdateTransactionPattern(PATTERN_NOT_COVERED
);
1830 return DoPartialCacheReadCompleted(result
);
1834 read_offset_
+= result
;
1835 } else if (result
== 0) { // End of file.
1837 cache_
->DoneReadingFromEntry(entry_
, this);
1840 return OnCacheReadError(result
, false);
1845 int HttpCache::Transaction::DoCacheWriteData(int num_bytes
) {
1846 next_state_
= STATE_CACHE_WRITE_DATA_COMPLETE
;
1847 write_len_
= num_bytes
;
1849 if (net_log_
.IsCapturing())
1850 net_log_
.BeginEvent(NetLog::TYPE_HTTP_CACHE_WRITE_DATA
);
1853 if (!entry_
|| !num_bytes
)
1856 int current_size
= entry_
->disk_entry
->GetDataSize(kResponseContentIndex
);
1857 return WriteToEntry(kResponseContentIndex
, current_size
, read_buf_
.get(),
1858 num_bytes
, io_callback_
);
1861 int HttpCache::Transaction::DoCacheWriteDataComplete(int result
) {
1863 if (net_log_
.IsCapturing()) {
1864 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_HTTP_CACHE_WRITE_DATA
,
1869 return ERR_UNEXPECTED
;
1871 if (result
!= write_len_
) {
1872 DLOG(ERROR
) << "failed to write response data to cache";
1873 DoneWritingToEntry(false);
1875 // We want to ignore errors writing to disk and just keep reading from
1877 result
= write_len_
;
1878 } else if (!done_reading_
&& entry_
) {
1879 int current_size
= entry_
->disk_entry
->GetDataSize(kResponseContentIndex
);
1880 int64 body_size
= response_
.headers
->GetContentLength();
1881 if (body_size
>= 0 && body_size
<= current_size
)
1882 done_reading_
= true;
1886 // This may be the last request.
1887 if (result
!= 0 || truncated_
||
1888 !(partial_
->IsLastRange() || mode_
== WRITE
)) {
1889 return DoPartialNetworkReadCompleted(result
);
1894 // End of file. This may be the result of a connection problem so see if we
1895 // have to keep the entry around to be flagged as truncated later on.
1896 if (done_reading_
|| !entry_
|| partial_
||
1897 response_
.headers
->GetContentLength() <= 0) {
1898 DoneWritingToEntry(true);
1905 int HttpCache::Transaction::DoCacheWriteTruncatedResponse() {
1906 next_state_
= STATE_CACHE_WRITE_TRUNCATED_RESPONSE_COMPLETE
;
1907 return WriteResponseInfoToEntry(true);
1910 int HttpCache::Transaction::DoCacheWriteTruncatedResponseComplete(int result
) {
1911 return OnWriteResponseInfoToEntryComplete(result
);
1914 //-----------------------------------------------------------------------------
1916 void HttpCache::Transaction::ReadCertChain() {
1918 GetCacheKeyForCert(response_
.ssl_info
.cert
->os_cert_handle());
1919 const X509Certificate::OSCertHandles
& intermediates
=
1920 response_
.ssl_info
.cert
->GetIntermediateCertificates();
1921 int dist_from_root
= intermediates
.size();
1923 scoped_refptr
<SharedChainData
> shared_chain_data(
1924 new SharedChainData(intermediates
.size() + 1, TimeTicks::Now()));
1925 cache_
->cert_cache()->GetCertificate(key
,
1926 base::Bind(&OnCertReadIOComplete
,
1929 shared_chain_data
));
1931 for (X509Certificate::OSCertHandles::const_iterator it
=
1932 intermediates
.begin();
1933 it
!= intermediates
.end();
1936 key
= GetCacheKeyForCert(*it
);
1937 cache_
->cert_cache()->GetCertificate(key
,
1938 base::Bind(&OnCertReadIOComplete
,
1940 false /* is not leaf */,
1941 shared_chain_data
));
1943 DCHECK_EQ(0, dist_from_root
);
1946 void HttpCache::Transaction::WriteCertChain() {
1947 const X509Certificate::OSCertHandles
& intermediates
=
1948 response_
.ssl_info
.cert
->GetIntermediateCertificates();
1949 int dist_from_root
= intermediates
.size();
1951 scoped_refptr
<SharedChainData
> shared_chain_data(
1952 new SharedChainData(intermediates
.size() + 1, TimeTicks::Now()));
1953 cache_
->cert_cache()->SetCertificate(
1954 response_
.ssl_info
.cert
->os_cert_handle(),
1955 base::Bind(&OnCertWriteIOComplete
,
1958 shared_chain_data
));
1959 for (X509Certificate::OSCertHandles::const_iterator it
=
1960 intermediates
.begin();
1961 it
!= intermediates
.end();
1964 cache_
->cert_cache()->SetCertificate(*it
,
1965 base::Bind(&OnCertWriteIOComplete
,
1967 false /* is not leaf */,
1968 shared_chain_data
));
1970 DCHECK_EQ(0, dist_from_root
);
1973 void HttpCache::Transaction::SetRequest(const BoundNetLog
& net_log
,
1974 const HttpRequestInfo
* request
) {
1977 effective_load_flags_
= request_
->load_flags
;
1979 if (cache_
->mode() == DISABLE
)
1980 effective_load_flags_
|= LOAD_DISABLE_CACHE
;
1982 // Some headers imply load flags. The order here is significant.
1984 // LOAD_DISABLE_CACHE : no cache read or write
1985 // LOAD_BYPASS_CACHE : no cache read
1986 // LOAD_VALIDATE_CACHE : no cache read unless validation
1988 // The former modes trump latter modes, so if we find a matching header we
1989 // can stop iterating kSpecialHeaders.
1991 static const struct {
1992 const HeaderNameAndValue
* search
;
1994 } kSpecialHeaders
[] = {
1995 { kPassThroughHeaders
, LOAD_DISABLE_CACHE
},
1996 { kForceFetchHeaders
, LOAD_BYPASS_CACHE
},
1997 { kForceValidateHeaders
, LOAD_VALIDATE_CACHE
},
2000 bool range_found
= false;
2001 bool external_validation_error
= false;
2002 bool special_headers
= false;
2004 if (request_
->extra_headers
.HasHeader(HttpRequestHeaders::kRange
))
2007 for (size_t i
= 0; i
< arraysize(kSpecialHeaders
); ++i
) {
2008 if (HeaderMatches(request_
->extra_headers
, kSpecialHeaders
[i
].search
)) {
2009 effective_load_flags_
|= kSpecialHeaders
[i
].load_flag
;
2010 special_headers
= true;
2015 // Check for conditionalization headers which may correspond with a
2016 // cache validation request.
2017 for (size_t i
= 0; i
< arraysize(kValidationHeaders
); ++i
) {
2018 const ValidationHeaderInfo
& info
= kValidationHeaders
[i
];
2019 std::string validation_value
;
2020 if (request_
->extra_headers
.GetHeader(
2021 info
.request_header_name
, &validation_value
)) {
2022 if (!external_validation_
.values
[i
].empty() ||
2023 validation_value
.empty()) {
2024 external_validation_error
= true;
2026 external_validation_
.values
[i
] = validation_value
;
2027 external_validation_
.initialized
= true;
2031 if (range_found
|| special_headers
|| external_validation_
.initialized
) {
2032 // Log the headers before request_ is modified.
2035 NetLog::TYPE_HTTP_CACHE_CALLER_REQUEST_HEADERS
,
2036 base::Bind(&HttpRequestHeaders::NetLogCallback
,
2037 base::Unretained(&request_
->extra_headers
), &empty
));
2040 // We don't support ranges and validation headers.
2041 if (range_found
&& external_validation_
.initialized
) {
2042 LOG(WARNING
) << "Byte ranges AND validation headers found.";
2043 effective_load_flags_
|= LOAD_DISABLE_CACHE
;
2046 // If there is more than one validation header, we can't treat this request as
2047 // a cache validation, since we don't know for sure which header the server
2048 // will give us a response for (and they could be contradictory).
2049 if (external_validation_error
) {
2050 LOG(WARNING
) << "Multiple or malformed validation headers found.";
2051 effective_load_flags_
|= LOAD_DISABLE_CACHE
;
2054 if (range_found
&& !(effective_load_flags_
& LOAD_DISABLE_CACHE
)) {
2055 UpdateTransactionPattern(PATTERN_NOT_COVERED
);
2056 partial_
.reset(new PartialData
);
2057 if (request_
->method
== "GET" && partial_
->Init(request_
->extra_headers
)) {
2058 // We will be modifying the actual range requested to the server, so
2059 // let's remove the header here.
2060 custom_request_
.reset(new HttpRequestInfo(*request_
));
2061 custom_request_
->extra_headers
.RemoveHeader(HttpRequestHeaders::kRange
);
2062 request_
= custom_request_
.get();
2063 partial_
->SetHeaders(custom_request_
->extra_headers
);
2065 // The range is invalid or we cannot handle it properly.
2066 VLOG(1) << "Invalid byte range found.";
2067 effective_load_flags_
|= LOAD_DISABLE_CACHE
;
2068 partial_
.reset(NULL
);
2073 bool HttpCache::Transaction::ShouldPassThrough() {
2074 // We may have a null disk_cache if there is an error we cannot recover from,
2075 // like not enough disk space, or sharing violations.
2076 if (!cache_
->disk_cache_
.get())
2079 if (effective_load_flags_
& LOAD_DISABLE_CACHE
)
2082 if (request_
->method
== "GET" || request_
->method
== "HEAD")
2085 if (request_
->method
== "POST" && request_
->upload_data_stream
&&
2086 request_
->upload_data_stream
->identifier()) {
2090 if (request_
->method
== "PUT" && request_
->upload_data_stream
)
2093 if (request_
->method
== "DELETE")
2099 int HttpCache::Transaction::BeginCacheRead() {
2100 // We don't support any combination of LOAD_ONLY_FROM_CACHE and byte ranges.
2101 if (response_
.headers
->response_code() == 206 || partial_
) {
2103 return ERR_CACHE_MISS
;
2106 if (request_
->method
== "HEAD")
2107 FixHeadersForHead();
2109 // We don't have the whole resource.
2111 return ERR_CACHE_MISS
;
2113 if (entry_
->disk_entry
->GetDataSize(kMetadataIndex
))
2114 next_state_
= STATE_CACHE_READ_METADATA
;
2119 int HttpCache::Transaction::BeginCacheValidation() {
2120 DCHECK_EQ(mode_
, READ_WRITE
);
2122 ValidationType required_validation
= RequiresValidation();
2124 bool skip_validation
= (required_validation
== VALIDATION_NONE
);
2126 if ((effective_load_flags_
& LOAD_SUPPORT_ASYNC_REVALIDATION
) &&
2127 required_validation
== VALIDATION_ASYNCHRONOUS
) {
2128 DCHECK_EQ(request_
->method
, "GET");
2129 skip_validation
= true;
2130 response_
.async_revalidation_required
= true;
2133 if (request_
->method
== "HEAD" &&
2134 (truncated_
|| response_
.headers
->response_code() == 206)) {
2136 if (skip_validation
)
2137 return SetupEntryForRead();
2140 next_state_
= STATE_SEND_REQUEST
;
2146 // Truncated entries can cause partial gets, so we shouldn't record this
2147 // load in histograms.
2148 UpdateTransactionPattern(PATTERN_NOT_COVERED
);
2149 skip_validation
= !partial_
->initial_validation();
2152 if (partial_
&& (is_sparse_
|| truncated_
) &&
2153 (!partial_
->IsCurrentRangeCached() || invalid_range_
)) {
2154 // Force revalidation for sparse or truncated entries. Note that we don't
2155 // want to ignore the regular validation logic just because a byte range was
2156 // part of the request.
2157 skip_validation
= false;
2160 if (skip_validation
) {
2161 UpdateTransactionPattern(PATTERN_ENTRY_USED
);
2162 return SetupEntryForRead();
2164 // Make the network request conditional, to see if we may reuse our cached
2165 // response. If we cannot do so, then we just resort to a normal fetch.
2166 // Our mode remains READ_WRITE for a conditional request. Even if the
2167 // conditionalization fails, we don't switch to WRITE mode until we
2168 // know we won't be falling back to using the cache entry in the
2169 // LOAD_FROM_CACHE_IF_OFFLINE case.
2170 if (!ConditionalizeRequest()) {
2171 couldnt_conditionalize_request_
= true;
2172 UpdateTransactionPattern(PATTERN_ENTRY_CANT_CONDITIONALIZE
);
2174 return DoRestartPartialRequest();
2176 DCHECK_NE(206, response_
.headers
->response_code());
2178 next_state_
= STATE_SEND_REQUEST
;
2183 int HttpCache::Transaction::BeginPartialCacheValidation() {
2184 DCHECK_EQ(mode_
, READ_WRITE
);
2186 if (response_
.headers
->response_code() != 206 && !partial_
&& !truncated_
)
2187 return BeginCacheValidation();
2189 // Partial requests should not be recorded in histograms.
2190 UpdateTransactionPattern(PATTERN_NOT_COVERED
);
2191 if (request_
->method
== "HEAD")
2192 return BeginCacheValidation();
2194 if (!range_requested_
) {
2195 // The request is not for a range, but we have stored just ranges.
2197 partial_
.reset(new PartialData());
2198 partial_
->SetHeaders(request_
->extra_headers
);
2199 if (!custom_request_
.get()) {
2200 custom_request_
.reset(new HttpRequestInfo(*request_
));
2201 request_
= custom_request_
.get();
2205 next_state_
= STATE_CACHE_QUERY_DATA
;
2209 // This should only be called once per request.
2210 int HttpCache::Transaction::ValidateEntryHeadersAndContinue() {
2211 DCHECK_EQ(mode_
, READ_WRITE
);
2213 if (!partial_
->UpdateFromStoredHeaders(
2214 response_
.headers
.get(), entry_
->disk_entry
, truncated_
)) {
2215 return DoRestartPartialRequest();
2218 if (response_
.headers
->response_code() == 206)
2221 if (!partial_
->IsRequestedRangeOK()) {
2222 // The stored data is fine, but the request may be invalid.
2223 invalid_range_
= true;
2226 next_state_
= STATE_START_PARTIAL_CACHE_VALIDATION
;
2230 int HttpCache::Transaction::BeginExternallyConditionalizedRequest() {
2231 DCHECK_EQ(UPDATE
, mode_
);
2232 DCHECK(external_validation_
.initialized
);
2234 for (size_t i
= 0; i
< arraysize(kValidationHeaders
); i
++) {
2235 if (external_validation_
.values
[i
].empty())
2237 // Retrieve either the cached response's "etag" or "last-modified" header.
2238 std::string validator
;
2239 response_
.headers
->EnumerateHeader(
2241 kValidationHeaders
[i
].related_response_header_name
,
2244 if (response_
.headers
->response_code() != 200 || truncated_
||
2245 validator
.empty() || validator
!= external_validation_
.values
[i
]) {
2246 // The externally conditionalized request is not a validation request
2247 // for our existing cache entry. Proceed with caching disabled.
2248 UpdateTransactionPattern(PATTERN_NOT_COVERED
);
2249 DoneWritingToEntry(true);
2253 // TODO(ricea): This calculation is expensive to perform just to collect
2254 // statistics. Either remove it or use the result, depending on the result of
2256 ExternallyConditionalizedType type
=
2257 EXTERNALLY_CONDITIONALIZED_CACHE_USABLE
;
2259 type
= EXTERNALLY_CONDITIONALIZED_MISMATCHED_VALIDATORS
;
2260 else if (RequiresValidation() != VALIDATION_NONE
)
2261 type
= EXTERNALLY_CONDITIONALIZED_CACHE_REQUIRES_VALIDATION
;
2263 // TODO(ricea): Add CACHE_USABLE_STALE once stale-while-revalidate CL landed.
2264 // TODO(ricea): Either remove this histogram or make it permanent by M40.
2265 UMA_HISTOGRAM_ENUMERATION("HttpCache.ExternallyConditionalized",
2267 EXTERNALLY_CONDITIONALIZED_MAX
);
2269 next_state_
= STATE_SEND_REQUEST
;
2273 int HttpCache::Transaction::RestartNetworkRequest() {
2274 DCHECK(mode_
& WRITE
|| mode_
== NONE
);
2275 DCHECK(network_trans_
.get());
2276 DCHECK_EQ(STATE_NONE
, next_state_
);
2278 next_state_
= STATE_SEND_REQUEST_COMPLETE
;
2279 int rv
= network_trans_
->RestartIgnoringLastError(io_callback_
);
2280 if (rv
!= ERR_IO_PENDING
)
2285 int HttpCache::Transaction::RestartNetworkRequestWithCertificate(
2286 X509Certificate
* client_cert
) {
2287 DCHECK(mode_
& WRITE
|| mode_
== NONE
);
2288 DCHECK(network_trans_
.get());
2289 DCHECK_EQ(STATE_NONE
, next_state_
);
2291 next_state_
= STATE_SEND_REQUEST_COMPLETE
;
2292 int rv
= network_trans_
->RestartWithCertificate(client_cert
, io_callback_
);
2293 if (rv
!= ERR_IO_PENDING
)
2298 int HttpCache::Transaction::RestartNetworkRequestWithAuth(
2299 const AuthCredentials
& credentials
) {
2300 DCHECK(mode_
& WRITE
|| mode_
== NONE
);
2301 DCHECK(network_trans_
.get());
2302 DCHECK_EQ(STATE_NONE
, next_state_
);
2304 next_state_
= STATE_SEND_REQUEST_COMPLETE
;
2305 int rv
= network_trans_
->RestartWithAuth(credentials
, io_callback_
);
2306 if (rv
!= ERR_IO_PENDING
)
2311 ValidationType
HttpCache::Transaction::RequiresValidation() {
2312 // TODO(darin): need to do more work here:
2313 // - make sure we have a matching request method
2314 // - watch out for cached responses that depend on authentication
2316 if (response_
.vary_data
.is_valid() &&
2317 !response_
.vary_data
.MatchesRequest(*request_
,
2318 *response_
.headers
.get())) {
2319 vary_mismatch_
= true;
2320 return VALIDATION_SYNCHRONOUS
;
2323 if (effective_load_flags_
& LOAD_PREFERRING_CACHE
)
2324 return VALIDATION_NONE
;
2326 if (response_
.unused_since_prefetch
&&
2327 !(effective_load_flags_
& LOAD_PREFETCH
) &&
2328 response_
.headers
->GetCurrentAge(
2329 response_
.request_time
, response_
.response_time
,
2330 cache_
->clock_
->Now()) < TimeDelta::FromMinutes(kPrefetchReuseMins
)) {
2331 // The first use of a resource after prefetch within a short window skips
2333 return VALIDATION_NONE
;
2336 if (effective_load_flags_
& LOAD_VALIDATE_CACHE
)
2337 return VALIDATION_SYNCHRONOUS
;
2339 if (request_
->method
== "PUT" || request_
->method
== "DELETE")
2340 return VALIDATION_SYNCHRONOUS
;
2342 ValidationType validation_required_by_headers
=
2343 response_
.headers
->RequiresValidation(response_
.request_time
,
2344 response_
.response_time
,
2345 cache_
->clock_
->Now());
2347 if (validation_required_by_headers
== VALIDATION_ASYNCHRONOUS
) {
2348 // Asynchronous revalidation is only supported for GET and HEAD methods.
2349 if (request_
->method
!= "GET" && request_
->method
!= "HEAD")
2350 return VALIDATION_SYNCHRONOUS
;
2353 return validation_required_by_headers
;
2356 bool HttpCache::Transaction::ConditionalizeRequest() {
2357 DCHECK(response_
.headers
.get());
2359 if (request_
->method
== "PUT" || request_
->method
== "DELETE")
2362 // This only makes sense for cached 200 or 206 responses.
2363 if (response_
.headers
->response_code() != 200 &&
2364 response_
.headers
->response_code() != 206) {
2368 if (fail_conditionalization_for_test_
)
2371 DCHECK(response_
.headers
->response_code() != 206 ||
2372 response_
.headers
->HasStrongValidators());
2374 // Just use the first available ETag and/or Last-Modified header value.
2375 // TODO(darin): Or should we use the last?
2377 std::string etag_value
;
2378 if (response_
.headers
->GetHttpVersion() >= HttpVersion(1, 1))
2379 response_
.headers
->EnumerateHeader(NULL
, "etag", &etag_value
);
2381 std::string last_modified_value
;
2382 if (!vary_mismatch_
) {
2383 response_
.headers
->EnumerateHeader(NULL
, "last-modified",
2384 &last_modified_value
);
2387 if (etag_value
.empty() && last_modified_value
.empty())
2391 // Need to customize the request, so this forces us to allocate :(
2392 custom_request_
.reset(new HttpRequestInfo(*request_
));
2393 request_
= custom_request_
.get();
2395 DCHECK(custom_request_
.get());
2398 partial_
&& !partial_
->IsCurrentRangeCached() && !invalid_range_
;
2400 if (!use_if_range
) {
2401 // stale-while-revalidate is not useful when we only have a partial response
2402 // cached, so don't set the header in that case.
2403 HttpResponseHeaders::FreshnessLifetimes lifetimes
=
2404 response_
.headers
->GetFreshnessLifetimes(response_
.response_time
);
2405 if (lifetimes
.staleness
> TimeDelta()) {
2406 TimeDelta current_age
= response_
.headers
->GetCurrentAge(
2407 response_
.request_time
, response_
.response_time
,
2408 cache_
->clock_
->Now());
2410 custom_request_
->extra_headers
.SetHeader(
2412 base::StringPrintf("max-age=%" PRId64
2413 ",stale-while-revalidate=%" PRId64
",age=%" PRId64
,
2414 lifetimes
.freshness
.InSeconds(),
2415 lifetimes
.staleness
.InSeconds(),
2416 current_age
.InSeconds()));
2420 if (!etag_value
.empty()) {
2422 // We don't want to switch to WRITE mode if we don't have this block of a
2423 // byte-range request because we may have other parts cached.
2424 custom_request_
->extra_headers
.SetHeader(
2425 HttpRequestHeaders::kIfRange
, etag_value
);
2427 custom_request_
->extra_headers
.SetHeader(
2428 HttpRequestHeaders::kIfNoneMatch
, etag_value
);
2430 // For byte-range requests, make sure that we use only one way to validate
2432 if (partial_
&& !partial_
->IsCurrentRangeCached())
2436 if (!last_modified_value
.empty()) {
2438 custom_request_
->extra_headers
.SetHeader(
2439 HttpRequestHeaders::kIfRange
, last_modified_value
);
2441 custom_request_
->extra_headers
.SetHeader(
2442 HttpRequestHeaders::kIfModifiedSince
, last_modified_value
);
2449 // We just received some headers from the server. We may have asked for a range,
2450 // in which case partial_ has an object. This could be the first network request
2451 // we make to fulfill the original request, or we may be already reading (from
2452 // the net and / or the cache). If we are not expecting a certain response, we
2453 // just bypass the cache for this request (but again, maybe we are reading), and
2454 // delete partial_ (so we are not able to "fix" the headers that we return to
2455 // the user). This results in either a weird response for the caller (we don't
2456 // expect it after all), or maybe a range that was not exactly what it was asked
2459 // If the server is simply telling us that the resource has changed, we delete
2460 // the cached entry and restart the request as the caller intended (by returning
2461 // false from this method). However, we may not be able to do that at any point,
2462 // for instance if we already returned the headers to the user.
2464 // WARNING: Whenever this code returns false, it has to make sure that the next
2465 // time it is called it will return true so that we don't keep retrying the
2467 bool HttpCache::Transaction::ValidatePartialResponse() {
2468 const HttpResponseHeaders
* headers
= new_response_
->headers
.get();
2469 int response_code
= headers
->response_code();
2470 bool partial_response
= (response_code
== 206);
2471 handling_206_
= false;
2473 if (!entry_
|| request_
->method
!= "GET")
2476 if (invalid_range_
) {
2477 // We gave up trying to match this request with the stored data. If the
2478 // server is ok with the request, delete the entry, otherwise just ignore
2481 if (partial_response
|| response_code
== 200) {
2482 DoomPartialEntry(true);
2485 if (response_code
== 304) {
2486 // Change the response code of the request to be 416 (Requested range
2487 // not satisfiable).
2488 response_
= *new_response_
;
2489 partial_
->FixResponseHeaders(response_
.headers
.get(), false);
2491 IgnoreRangeRequest();
2497 // We are not expecting 206 but we may have one.
2498 if (partial_response
)
2499 IgnoreRangeRequest();
2504 // TODO(rvargas): Do we need to consider other results here?.
2505 bool failure
= response_code
== 200 || response_code
== 416;
2507 if (partial_
->IsCurrentRangeCached()) {
2508 // We asked for "If-None-Match: " so a 206 means a new object.
2509 if (partial_response
)
2512 if (response_code
== 304 && partial_
->ResponseHeadersOK(headers
))
2515 // We asked for "If-Range: " so a 206 means just another range.
2516 if (partial_response
) {
2517 if (partial_
->ResponseHeadersOK(headers
)) {
2518 handling_206_
= true;
2525 if (!reading_
&& !is_sparse_
&& !partial_response
) {
2526 // See if we can ignore the fact that we issued a byte range request.
2527 // If the server sends 200, just store it. If it sends an error, redirect
2528 // or something else, we may store the response as long as we didn't have
2529 // anything already stored.
2530 if (response_code
== 200 ||
2531 (!truncated_
&& response_code
!= 304 && response_code
!= 416)) {
2532 // The server is sending something else, and we can save it.
2533 DCHECK((truncated_
&& !partial_
->IsLastRange()) || range_requested_
);
2540 // 304 is not expected here, but we'll spare the entry (unless it was
2547 // We cannot truncate this entry, it has to be deleted.
2548 UpdateTransactionPattern(PATTERN_NOT_COVERED
);
2550 if (is_sparse_
|| truncated_
) {
2551 // There was something cached to start with, either sparsed data (206), or
2552 // a truncated 200, which means that we probably modified the request,
2553 // adding a byte range or modifying the range requested by the caller.
2554 if (!reading_
&& !partial_
->IsLastRange()) {
2555 // We have not returned anything to the caller yet so it should be safe
2556 // to issue another network request, this time without us messing up the
2558 ResetPartialState(true);
2561 LOG(WARNING
) << "Failed to revalidate partial entry";
2563 DoomPartialEntry(true);
2567 IgnoreRangeRequest();
2571 void HttpCache::Transaction::IgnoreRangeRequest() {
2572 // We have a problem. We may or may not be reading already (in which case we
2573 // returned the headers), but we'll just pretend that this request is not
2574 // using the cache and see what happens. Most likely this is the first
2575 // response from the server (it's not changing its mind midway, right?).
2576 UpdateTransactionPattern(PATTERN_NOT_COVERED
);
2578 DoneWritingToEntry(mode_
!= WRITE
);
2579 else if (mode_
& READ
&& entry_
)
2580 cache_
->DoneReadingFromEntry(entry_
, this);
2582 partial_
.reset(NULL
);
2587 void HttpCache::Transaction::FixHeadersForHead() {
2588 if (response_
.headers
->response_code() == 206) {
2589 response_
.headers
->RemoveHeader("Content-Range");
2590 response_
.headers
->ReplaceStatusLine("HTTP/1.1 200 OK");
2594 int HttpCache::Transaction::SetupEntryForRead() {
2596 ResetNetworkTransaction();
2598 if (truncated_
|| is_sparse_
|| !invalid_range_
) {
2599 // We are going to return the saved response headers to the caller, so
2600 // we may need to adjust them first.
2601 next_state_
= STATE_PARTIAL_HEADERS_RECEIVED
;
2607 cache_
->ConvertWriterToReader(entry_
);
2610 if (request_
->method
== "HEAD")
2611 FixHeadersForHead();
2613 if (entry_
->disk_entry
->GetDataSize(kMetadataIndex
))
2614 next_state_
= STATE_CACHE_READ_METADATA
;
2618 int HttpCache::Transaction::WriteToEntry(int index
, int offset
,
2619 IOBuffer
* data
, int data_len
,
2620 const CompletionCallback
& callback
) {
2625 if (!partial_
|| !data_len
) {
2626 rv
= entry_
->disk_entry
->WriteData(index
, offset
, data
, data_len
, callback
,
2629 rv
= partial_
->CacheWrite(entry_
->disk_entry
, data
, data_len
, callback
);
2634 int HttpCache::Transaction::WriteResponseInfoToEntry(bool truncated
) {
2638 if (net_log_
.IsCapturing())
2639 net_log_
.BeginEvent(NetLog::TYPE_HTTP_CACHE_WRITE_INFO
);
2641 // Do not cache no-store content. Do not cache content with cert errors
2642 // either. This is to prevent not reporting net errors when loading a
2643 // resource from the cache. When we load a page over HTTPS with a cert error
2644 // we show an SSL blocking page. If the user clicks proceed we reload the
2645 // resource ignoring the errors. The loaded resource is then cached. If that
2646 // resource is subsequently loaded from the cache, no net error is reported
2647 // (even though the cert status contains the actual errors) and no SSL
2648 // blocking page is shown. An alternative would be to reverse-map the cert
2649 // status to a net error and replay the net error.
2650 if ((response_
.headers
->HasHeaderValue("cache-control", "no-store")) ||
2651 IsCertStatusError(response_
.ssl_info
.cert_status
)) {
2652 DoneWritingToEntry(false);
2653 if (net_log_
.IsCapturing())
2654 net_log_
.EndEvent(NetLog::TYPE_HTTP_CACHE_WRITE_INFO
);
2658 // cert_cache() will be null if the CertCacheTrial field trial is disabled.
2659 if (cache_
->cert_cache() && response_
.ssl_info
.is_valid())
2663 DCHECK_EQ(200, response_
.headers
->response_code());
2665 // When writing headers, we normally only write the non-transient headers.
2666 bool skip_transient_headers
= true;
2667 scoped_refptr
<PickledIOBuffer
> data(new PickledIOBuffer());
2668 response_
.Persist(data
->pickle(), skip_transient_headers
, truncated
);
2671 io_buf_len_
= data
->pickle()->size();
2672 return entry_
->disk_entry
->WriteData(kResponseInfoIndex
, 0, data
.get(),
2673 io_buf_len_
, io_callback_
, true);
2676 int HttpCache::Transaction::OnWriteResponseInfoToEntryComplete(int result
) {
2679 if (net_log_
.IsCapturing()) {
2680 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_HTTP_CACHE_WRITE_INFO
,
2684 if (result
!= io_buf_len_
) {
2685 DLOG(ERROR
) << "failed to write response info to cache";
2686 DoneWritingToEntry(false);
2691 void HttpCache::Transaction::DoneWritingToEntry(bool success
) {
2697 cache_
->DoneWritingToEntry(entry_
, success
);
2699 mode_
= NONE
; // switch to 'pass through' mode
2702 int HttpCache::Transaction::OnCacheReadError(int result
, bool restart
) {
2703 DLOG(ERROR
) << "ReadData failed: " << result
;
2704 const int result_for_histogram
= std::max(0, -result
);
2706 UMA_HISTOGRAM_SPARSE_SLOWLY("HttpCache.ReadErrorRestartable",
2707 result_for_histogram
);
2709 UMA_HISTOGRAM_SPARSE_SLOWLY("HttpCache.ReadErrorNonRestartable",
2710 result_for_histogram
);
2713 // Avoid using this entry in the future.
2715 cache_
->DoomActiveEntry(cache_key_
);
2719 DCHECK(!network_trans_
.get());
2720 cache_
->DoneWithEntry(entry_
, this, false);
2724 next_state_
= STATE_GET_BACKEND
;
2728 return ERR_CACHE_READ_FAILURE
;
2731 void HttpCache::Transaction::OnAddToEntryTimeout(base::TimeTicks start_time
) {
2732 if (entry_lock_waiting_since_
!= start_time
)
2735 DCHECK_EQ(next_state_
, STATE_ADD_TO_ENTRY_COMPLETE
);
2740 cache_
->RemovePendingTransaction(this);
2741 OnIOComplete(ERR_CACHE_LOCK_TIMEOUT
);
2744 void HttpCache::Transaction::DoomPartialEntry(bool delete_object
) {
2745 DVLOG(2) << "DoomPartialEntry";
2746 int rv
= cache_
->DoomEntry(cache_key_
, NULL
);
2748 cache_
->DoneWithEntry(entry_
, this, false);
2753 partial_
.reset(NULL
);
2756 int HttpCache::Transaction::DoPartialNetworkReadCompleted(int result
) {
2757 partial_
->OnNetworkReadCompleted(result
);
2760 // We need to move on to the next range.
2761 ResetNetworkTransaction();
2762 next_state_
= STATE_START_PARTIAL_CACHE_VALIDATION
;
2767 int HttpCache::Transaction::DoPartialCacheReadCompleted(int result
) {
2768 partial_
->OnCacheReadCompleted(result
);
2770 if (result
== 0 && mode_
== READ_WRITE
) {
2771 // We need to move on to the next range.
2772 next_state_
= STATE_START_PARTIAL_CACHE_VALIDATION
;
2773 } else if (result
< 0) {
2774 return OnCacheReadError(result
, false);
2779 int HttpCache::Transaction::DoRestartPartialRequest() {
2780 // The stored data cannot be used. Get rid of it and restart this request.
2781 net_log_
.AddEvent(NetLog::TYPE_HTTP_CACHE_RESTART_PARTIAL_REQUEST
);
2783 // WRITE + Doom + STATE_INIT_ENTRY == STATE_CREATE_ENTRY (without an attempt
2784 // to Doom the entry again).
2786 ResetPartialState(!range_requested_
);
2787 next_state_
= STATE_CREATE_ENTRY
;
2791 void HttpCache::Transaction::ResetPartialState(bool delete_object
) {
2792 partial_
->RestoreHeaders(&custom_request_
->extra_headers
);
2793 DoomPartialEntry(delete_object
);
2795 if (!delete_object
) {
2796 // The simplest way to re-initialize partial_ is to create a new object.
2797 partial_
.reset(new PartialData());
2798 if (partial_
->Init(request_
->extra_headers
))
2799 partial_
->SetHeaders(custom_request_
->extra_headers
);
2805 void HttpCache::Transaction::ResetNetworkTransaction() {
2806 DCHECK(!old_network_trans_load_timing_
);
2807 DCHECK(network_trans_
);
2808 LoadTimingInfo load_timing
;
2809 if (network_trans_
->GetLoadTimingInfo(&load_timing
))
2810 old_network_trans_load_timing_
.reset(new LoadTimingInfo(load_timing
));
2811 total_received_bytes_
+= network_trans_
->GetTotalReceivedBytes();
2812 total_sent_bytes_
+= network_trans_
->GetTotalSentBytes();
2813 ConnectionAttempts attempts
;
2814 network_trans_
->GetConnectionAttempts(&attempts
);
2815 for (const auto& attempt
: attempts
)
2816 old_connection_attempts_
.push_back(attempt
);
2817 network_trans_
.reset();
2820 // Histogram data from the end of 2010 show the following distribution of
2821 // response headers:
2823 // Content-Length............... 87%
2824 // Date......................... 98%
2825 // Last-Modified................ 49%
2826 // Etag......................... 19%
2827 // Accept-Ranges: bytes......... 25%
2828 // Accept-Ranges: none.......... 0.4%
2829 // Strong Validator............. 50%
2830 // Strong Validator + ranges.... 24%
2831 // Strong Validator + CL........ 49%
2833 bool HttpCache::Transaction::CanResume(bool has_data
) {
2834 // Double check that there is something worth keeping.
2835 if (has_data
&& !entry_
->disk_entry
->GetDataSize(kResponseContentIndex
))
2838 if (request_
->method
!= "GET")
2841 // Note that if this is a 206, content-length was already fixed after calling
2842 // PartialData::ResponseHeadersOK().
2843 if (response_
.headers
->GetContentLength() <= 0 ||
2844 response_
.headers
->HasHeaderValue("Accept-Ranges", "none") ||
2845 !response_
.headers
->HasStrongValidators()) {
2852 void HttpCache::Transaction::UpdateTransactionPattern(
2853 TransactionPattern new_transaction_pattern
) {
2854 if (transaction_pattern_
== PATTERN_NOT_COVERED
)
2856 DCHECK(transaction_pattern_
== PATTERN_UNDEFINED
||
2857 new_transaction_pattern
== PATTERN_NOT_COVERED
);
2858 transaction_pattern_
= new_transaction_pattern
;
2861 void HttpCache::Transaction::RecordHistograms() {
2862 DCHECK_NE(PATTERN_UNDEFINED
, transaction_pattern_
);
2863 if (!cache_
.get() || !cache_
->GetCurrentBackend() ||
2864 cache_
->GetCurrentBackend()->GetCacheType() != DISK_CACHE
||
2865 cache_
->mode() != NORMAL
|| request_
->method
!= "GET") {
2868 UMA_HISTOGRAM_ENUMERATION(
2869 "HttpCache.Pattern", transaction_pattern_
, PATTERN_MAX
);
2870 if (transaction_pattern_
== PATTERN_NOT_COVERED
)
2872 DCHECK(!range_requested_
);
2873 DCHECK(!first_cache_access_since_
.is_null());
2875 TimeDelta total_time
= base::TimeTicks::Now() - first_cache_access_since_
;
2877 UMA_HISTOGRAM_TIMES("HttpCache.AccessToDone", total_time
);
2879 bool did_send_request
= !send_request_since_
.is_null();
2881 (did_send_request
&&
2882 (transaction_pattern_
== PATTERN_ENTRY_NOT_CACHED
||
2883 transaction_pattern_
== PATTERN_ENTRY_VALIDATED
||
2884 transaction_pattern_
== PATTERN_ENTRY_UPDATED
||
2885 transaction_pattern_
== PATTERN_ENTRY_CANT_CONDITIONALIZE
)) ||
2886 (!did_send_request
&& transaction_pattern_
== PATTERN_ENTRY_USED
));
2888 if (!did_send_request
) {
2889 DCHECK(transaction_pattern_
== PATTERN_ENTRY_USED
);
2890 UMA_HISTOGRAM_TIMES("HttpCache.AccessToDone.Used", total_time
);
2894 TimeDelta before_send_time
= send_request_since_
- first_cache_access_since_
;
2895 int64 before_send_percent
= (total_time
.ToInternalValue() == 0) ?
2896 0 : before_send_time
* 100 / total_time
;
2897 DCHECK_GE(before_send_percent
, 0);
2898 DCHECK_LE(before_send_percent
, 100);
2899 base::HistogramBase::Sample before_send_sample
=
2900 static_cast<base::HistogramBase::Sample
>(before_send_percent
);
2902 UMA_HISTOGRAM_TIMES("HttpCache.AccessToDone.SentRequest", total_time
);
2903 UMA_HISTOGRAM_TIMES("HttpCache.BeforeSend", before_send_time
);
2904 UMA_HISTOGRAM_PERCENTAGE("HttpCache.PercentBeforeSend", before_send_sample
);
2906 // TODO(gavinp): Remove or minimize these histograms, particularly the ones
2907 // below this comment after we have received initial data.
2908 switch (transaction_pattern_
) {
2909 case PATTERN_ENTRY_CANT_CONDITIONALIZE
: {
2910 UMA_HISTOGRAM_TIMES("HttpCache.BeforeSend.CantConditionalize",
2912 UMA_HISTOGRAM_PERCENTAGE("HttpCache.PercentBeforeSend.CantConditionalize",
2913 before_send_sample
);
2916 case PATTERN_ENTRY_NOT_CACHED
: {
2917 UMA_HISTOGRAM_TIMES("HttpCache.BeforeSend.NotCached", before_send_time
);
2918 UMA_HISTOGRAM_PERCENTAGE("HttpCache.PercentBeforeSend.NotCached",
2919 before_send_sample
);
2922 case PATTERN_ENTRY_VALIDATED
: {
2923 UMA_HISTOGRAM_TIMES("HttpCache.BeforeSend.Validated", before_send_time
);
2924 UMA_HISTOGRAM_PERCENTAGE("HttpCache.PercentBeforeSend.Validated",
2925 before_send_sample
);
2928 case PATTERN_ENTRY_UPDATED
: {
2929 UMA_HISTOGRAM_TIMES("HttpCache.BeforeSend.Updated", before_send_time
);
2930 UMA_HISTOGRAM_PERCENTAGE("HttpCache.PercentBeforeSend.Updated",
2931 before_send_sample
);
2939 void HttpCache::Transaction::OnIOComplete(int result
) {