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/memory/ref_counted.h"
19 #include "base/metrics/field_trial.h"
20 #include "base/metrics/histogram.h"
21 #include "base/metrics/sparse_histogram.h"
22 #include "base/rand_util.h"
23 #include "base/strings/string_number_conversions.h"
24 #include "base/strings/string_util.h"
25 #include "base/time/time.h"
26 #include "net/base/completion_callback.h"
27 #include "net/base/io_buffer.h"
28 #include "net/base/load_flags.h"
29 #include "net/base/load_timing_info.h"
30 #include "net/base/net_errors.h"
31 #include "net/base/net_log.h"
32 #include "net/base/upload_data_stream.h"
33 #include "net/cert/cert_status_flags.h"
34 #include "net/disk_cache/disk_cache.h"
35 #include "net/http/http_network_session.h"
36 #include "net/http/http_request_info.h"
37 #include "net/http/http_response_headers.h"
38 #include "net/http/http_transaction.h"
39 #include "net/http/http_util.h"
40 #include "net/http/partial_data.h"
41 #include "net/ssl/ssl_cert_request_info.h"
42 #include "net/ssl/ssl_config_service.h"
45 using base::TimeDelta
;
46 using base::TimeTicks
;
50 // From http://tools.ietf.org/html/draft-ietf-httpbis-p6-cache-21#section-6
51 // a "non-error response" is one with a 2xx (Successful) or 3xx
52 // (Redirection) status code.
53 bool NonErrorResponse(int status_code
) {
54 int status_code_range
= status_code
/ 100;
55 return status_code_range
== 2 || status_code_range
== 3;
58 // Error codes that will be considered indicative of a page being offline/
59 // unreachable for LOAD_FROM_CACHE_IF_OFFLINE.
60 bool IsOfflineError(int error
) {
61 return (error
== net::ERR_NAME_NOT_RESOLVED
||
62 error
== net::ERR_INTERNET_DISCONNECTED
||
63 error
== net::ERR_ADDRESS_UNREACHABLE
||
64 error
== net::ERR_CONNECTION_TIMED_OUT
);
67 // Enum for UMA, indicating the status (with regard to offline mode) of
68 // a particular request.
69 enum RequestOfflineStatus
{
70 // A cache transaction hit in cache (data was present and not stale)
72 OFFLINE_STATUS_FRESH_CACHE
,
74 // A network request was required for a cache entry, and it succeeded.
75 OFFLINE_STATUS_NETWORK_SUCCEEDED
,
77 // A network request was required for a cache entry, and it failed with
78 // a non-offline error.
79 OFFLINE_STATUS_NETWORK_FAILED
,
81 // A network request was required for a cache entry, it failed with an
82 // offline error, and we could serve stale data if
83 // LOAD_FROM_CACHE_IF_OFFLINE was set.
84 OFFLINE_STATUS_DATA_AVAILABLE_OFFLINE
,
86 // A network request was required for a cache entry, it failed with
87 // an offline error, and there was no servable data in cache (even
89 OFFLINE_STATUS_DATA_UNAVAILABLE_OFFLINE
,
91 OFFLINE_STATUS_MAX_ENTRIES
94 void RecordOfflineStatus(int load_flags
, RequestOfflineStatus status
) {
95 // Restrict to main frame to keep statistics close to
96 // "would have shown them something useful if offline mode was enabled".
97 if (load_flags
& net::LOAD_MAIN_FRAME
) {
98 UMA_HISTOGRAM_ENUMERATION("HttpCache.OfflineStatus", status
,
99 OFFLINE_STATUS_MAX_ENTRIES
);
103 // TODO(rvargas): Remove once we get the data.
104 void RecordVaryHeaderHistogram(const net::HttpResponseInfo
* response
) {
111 VaryType vary
= VARY_NOT_PRESENT
;
112 if (response
->vary_data
.is_valid()) {
114 if (response
->headers
->HasHeaderValue("vary", "user-agent"))
117 UMA_HISTOGRAM_ENUMERATION("HttpCache.Vary", vary
, VARY_MAX
);
120 void RecordNoStoreHeaderHistogram(int load_flags
,
121 const net::HttpResponseInfo
* response
) {
122 if (load_flags
& net::LOAD_MAIN_FRAME
) {
123 UMA_HISTOGRAM_BOOLEAN(
124 "Net.MainFrameNoStore",
125 response
->headers
->HasHeaderValue("cache-control", "no-store"));
133 struct HeaderNameAndValue
{
138 // If the request includes one of these request headers, then avoid caching
139 // to avoid getting confused.
140 static const HeaderNameAndValue kPassThroughHeaders
[] = {
141 { "if-unmodified-since", NULL
}, // causes unexpected 412s
142 { "if-match", NULL
}, // causes unexpected 412s
143 { "if-range", NULL
},
147 struct ValidationHeaderInfo
{
148 const char* request_header_name
;
149 const char* related_response_header_name
;
152 static const ValidationHeaderInfo kValidationHeaders
[] = {
153 { "if-modified-since", "last-modified" },
154 { "if-none-match", "etag" },
157 // If the request includes one of these request headers, then avoid reusing
158 // our cached copy if any.
159 static const HeaderNameAndValue kForceFetchHeaders
[] = {
160 { "cache-control", "no-cache" },
161 { "pragma", "no-cache" },
165 // If the request includes one of these request headers, then force our
166 // cached copy (if any) to be revalidated before reusing it.
167 static const HeaderNameAndValue kForceValidateHeaders
[] = {
168 { "cache-control", "max-age=0" },
172 static bool HeaderMatches(const HttpRequestHeaders
& headers
,
173 const HeaderNameAndValue
* search
) {
174 for (; search
->name
; ++search
) {
175 std::string header_value
;
176 if (!headers
.GetHeader(search
->name
, &header_value
))
182 HttpUtil::ValuesIterator
v(header_value
.begin(), header_value
.end(), ',');
183 while (v
.GetNext()) {
184 if (LowerCaseEqualsASCII(v
.value_begin(), v
.value_end(), search
->value
))
191 //-----------------------------------------------------------------------------
193 HttpCache::Transaction::Transaction(
194 RequestPriority priority
,
196 : next_state_(STATE_NONE
),
199 cache_(cache
->GetWeakPtr()),
204 target_state_(STATE_NONE
),
206 invalid_range_(false),
209 range_requested_(false),
210 handling_206_(false),
211 cache_pending_(false),
212 done_reading_(false),
213 vary_mismatch_(false),
214 couldnt_conditionalize_request_(false),
215 bypass_lock_for_test_(false),
218 effective_load_flags_(0),
221 io_callback_(base::Bind(&Transaction::OnIOComplete
,
222 weak_factory_
.GetWeakPtr())),
223 transaction_pattern_(PATTERN_UNDEFINED
),
224 total_received_bytes_(0),
225 websocket_handshake_stream_base_create_helper_(NULL
) {
226 COMPILE_ASSERT(HttpCache::Transaction::kNumValidationHeaders
==
227 arraysize(kValidationHeaders
),
228 Invalid_number_of_validation_headers
);
231 HttpCache::Transaction::~Transaction() {
232 // We may have to issue another IO, but we should never invoke the callback_
238 bool cancel_request
= reading_
&& response_
.headers
;
239 if (cancel_request
) {
241 entry_
->disk_entry
->CancelSparseIO();
243 cancel_request
&= (response_
.headers
->response_code() == 200);
247 cache_
->DoneWithEntry(entry_
, this, cancel_request
);
248 } else if (cache_pending_
) {
249 cache_
->RemovePendingTransaction(this);
254 int HttpCache::Transaction::WriteMetadata(IOBuffer
* buf
, int buf_len
,
255 const CompletionCallback
& callback
) {
257 DCHECK_GT(buf_len
, 0);
258 DCHECK(!callback
.is_null());
259 if (!cache_
.get() || !entry_
)
260 return ERR_UNEXPECTED
;
262 // We don't need to track this operation for anything.
263 // It could be possible to check if there is something already written and
264 // avoid writing again (it should be the same, right?), but let's allow the
265 // caller to "update" the contents with something new.
266 return entry_
->disk_entry
->WriteData(kMetadataIndex
, 0, buf
, buf_len
,
270 bool HttpCache::Transaction::AddTruncatedFlag() {
271 DCHECK(mode_
& WRITE
|| mode_
== NONE
);
273 // Don't set the flag for sparse entries.
274 if (partial_
.get() && !truncated_
)
277 if (!CanResume(true))
280 // We may have received the whole resource already.
285 target_state_
= STATE_NONE
;
286 next_state_
= STATE_CACHE_WRITE_TRUNCATED_RESPONSE
;
291 LoadState
HttpCache::Transaction::GetWriterLoadState() const {
292 if (network_trans_
.get())
293 return network_trans_
->GetLoadState();
294 if (entry_
|| !request_
)
295 return LOAD_STATE_IDLE
;
296 return LOAD_STATE_WAITING_FOR_CACHE
;
299 const BoundNetLog
& HttpCache::Transaction::net_log() const {
303 int HttpCache::Transaction::Start(const HttpRequestInfo
* request
,
304 const CompletionCallback
& callback
,
305 const BoundNetLog
& net_log
) {
307 DCHECK(!callback
.is_null());
309 // Ensure that we only have one asynchronous call at a time.
310 DCHECK(callback_
.is_null());
312 DCHECK(!network_trans_
.get());
316 return ERR_UNEXPECTED
;
318 SetRequest(net_log
, request
);
320 // We have to wait until the backend is initialized so we start the SM.
321 next_state_
= STATE_GET_BACKEND
;
324 // Setting this here allows us to check for the existence of a callback_ to
325 // determine if we are still inside Start.
326 if (rv
== ERR_IO_PENDING
)
327 callback_
= callback
;
332 int HttpCache::Transaction::RestartIgnoringLastError(
333 const CompletionCallback
& callback
) {
334 DCHECK(!callback
.is_null());
336 // Ensure that we only have one asynchronous call at a time.
337 DCHECK(callback_
.is_null());
340 return ERR_UNEXPECTED
;
342 int rv
= RestartNetworkRequest();
344 if (rv
== ERR_IO_PENDING
)
345 callback_
= callback
;
350 int HttpCache::Transaction::RestartWithCertificate(
351 X509Certificate
* client_cert
,
352 const CompletionCallback
& callback
) {
353 DCHECK(!callback
.is_null());
355 // Ensure that we only have one asynchronous call at a time.
356 DCHECK(callback_
.is_null());
359 return ERR_UNEXPECTED
;
361 int rv
= RestartNetworkRequestWithCertificate(client_cert
);
363 if (rv
== ERR_IO_PENDING
)
364 callback_
= callback
;
369 int HttpCache::Transaction::RestartWithAuth(
370 const AuthCredentials
& credentials
,
371 const CompletionCallback
& callback
) {
372 DCHECK(auth_response_
.headers
.get());
373 DCHECK(!callback
.is_null());
375 // Ensure that we only have one asynchronous call at a time.
376 DCHECK(callback_
.is_null());
379 return ERR_UNEXPECTED
;
381 // Clear the intermediate response since we are going to start over.
382 auth_response_
= HttpResponseInfo();
384 int rv
= RestartNetworkRequestWithAuth(credentials
);
386 if (rv
== ERR_IO_PENDING
)
387 callback_
= callback
;
392 bool HttpCache::Transaction::IsReadyToRestartForAuth() {
393 if (!network_trans_
.get())
395 return network_trans_
->IsReadyToRestartForAuth();
398 int HttpCache::Transaction::Read(IOBuffer
* buf
, int buf_len
,
399 const CompletionCallback
& callback
) {
401 DCHECK_GT(buf_len
, 0);
402 DCHECK(!callback
.is_null());
404 DCHECK(callback_
.is_null());
407 return ERR_UNEXPECTED
;
409 // If we have an intermediate auth response at this point, then it means the
410 // user wishes to read the network response (the error page). If there is a
411 // previous response in the cache then we should leave it intact.
412 if (auth_response_
.headers
.get() && mode_
!= NONE
) {
413 UpdateTransactionPattern(PATTERN_NOT_COVERED
);
414 DCHECK(mode_
& WRITE
);
415 DoneWritingToEntry(mode_
== READ_WRITE
);
424 DCHECK(partial_
.get());
425 if (!network_trans_
.get()) {
426 // We are just reading from the cache, but we may be writing later.
427 rv
= ReadFromEntry(buf
, buf_len
);
432 DCHECK(network_trans_
.get());
433 rv
= ReadFromNetwork(buf
, buf_len
);
436 rv
= ReadFromEntry(buf
, buf_len
);
443 if (rv
== ERR_IO_PENDING
) {
444 DCHECK(callback_
.is_null());
445 callback_
= callback
;
450 void HttpCache::Transaction::StopCaching() {
451 // We really don't know where we are now. Hopefully there is no operation in
452 // progress, but nothing really prevents this method to be called after we
453 // returned ERR_IO_PENDING. We cannot attempt to truncate the entry at this
454 // point because we need the state machine for that (and even if we are really
455 // free, that would be an asynchronous operation). In other words, keep the
456 // entry how it is (it will be marked as truncated at destruction), and let
457 // the next piece of code that executes know that we are now reading directly
459 // TODO(mmenke): This doesn't release the lock on the cache entry, so a
460 // future request for the resource will be blocked on this one.
462 if (cache_
.get() && entry_
&& (mode_
& WRITE
) && network_trans_
.get() &&
463 !is_sparse_
&& !range_requested_
) {
468 bool HttpCache::Transaction::GetFullRequestHeaders(
469 HttpRequestHeaders
* headers
) const {
471 return network_trans_
->GetFullRequestHeaders(headers
);
473 // TODO(ttuttle): Read headers from cache.
477 int64
HttpCache::Transaction::GetTotalReceivedBytes() const {
478 int64 total_received_bytes
= total_received_bytes_
;
480 total_received_bytes
+= network_trans_
->GetTotalReceivedBytes();
481 return total_received_bytes
;
484 void HttpCache::Transaction::DoneReading() {
485 if (cache_
.get() && entry_
) {
486 DCHECK_NE(mode_
, UPDATE
);
488 DoneWritingToEntry(true);
489 } else if (mode_
& READ
) {
490 // It is necessary to check mode_ & READ because it is possible
491 // for mode_ to be NONE and entry_ non-NULL with a write entry
492 // if StopCaching was called.
493 cache_
->DoneReadingFromEntry(entry_
, this);
499 const HttpResponseInfo
* HttpCache::Transaction::GetResponseInfo() const {
500 // Null headers means we encountered an error or haven't a response yet
501 if (auth_response_
.headers
.get())
502 return &auth_response_
;
503 return (response_
.headers
.get() || response_
.ssl_info
.cert
.get() ||
504 response_
.cert_request_info
.get())
509 LoadState
HttpCache::Transaction::GetLoadState() const {
510 LoadState state
= GetWriterLoadState();
511 if (state
!= LOAD_STATE_WAITING_FOR_CACHE
)
515 return cache_
->GetLoadStateForPendingTransaction(this);
517 return LOAD_STATE_IDLE
;
520 UploadProgress
HttpCache::Transaction::GetUploadProgress() const {
521 if (network_trans_
.get())
522 return network_trans_
->GetUploadProgress();
523 return final_upload_progress_
;
526 void HttpCache::Transaction::SetQuicServerInfo(
527 QuicServerInfo
* quic_server_info
) {}
529 bool HttpCache::Transaction::GetLoadTimingInfo(
530 LoadTimingInfo
* load_timing_info
) const {
532 return network_trans_
->GetLoadTimingInfo(load_timing_info
);
534 if (old_network_trans_load_timing_
) {
535 *load_timing_info
= *old_network_trans_load_timing_
;
539 if (first_cache_access_since_
.is_null())
542 // If the cache entry was opened, return that time.
543 load_timing_info
->send_start
= first_cache_access_since_
;
544 // This time doesn't make much sense when reading from the cache, so just use
545 // the same time as send_start.
546 load_timing_info
->send_end
= first_cache_access_since_
;
550 void HttpCache::Transaction::SetPriority(RequestPriority priority
) {
551 priority_
= priority
;
553 network_trans_
->SetPriority(priority_
);
556 void HttpCache::Transaction::SetWebSocketHandshakeStreamCreateHelper(
557 WebSocketHandshakeStreamBase::CreateHelper
* create_helper
) {
558 websocket_handshake_stream_base_create_helper_
= create_helper
;
560 network_trans_
->SetWebSocketHandshakeStreamCreateHelper(create_helper
);
563 void HttpCache::Transaction::SetBeforeNetworkStartCallback(
564 const BeforeNetworkStartCallback
& callback
) {
565 DCHECK(!network_trans_
);
566 before_network_start_callback_
= callback
;
569 void HttpCache::Transaction::SetBeforeProxyHeadersSentCallback(
570 const BeforeProxyHeadersSentCallback
& callback
) {
571 DCHECK(!network_trans_
);
572 before_proxy_headers_sent_callback_
= callback
;
575 int HttpCache::Transaction::ResumeNetworkStart() {
577 return network_trans_
->ResumeNetworkStart();
578 return ERR_UNEXPECTED
;
581 //-----------------------------------------------------------------------------
583 void HttpCache::Transaction::DoCallback(int rv
) {
584 DCHECK(rv
!= ERR_IO_PENDING
);
585 DCHECK(!callback_
.is_null());
587 read_buf_
= NULL
; // Release the buffer before invoking the callback.
589 // Since Run may result in Read being called, clear callback_ up front.
590 CompletionCallback c
= callback_
;
595 int HttpCache::Transaction::HandleResult(int rv
) {
596 DCHECK(rv
!= ERR_IO_PENDING
);
597 if (!callback_
.is_null())
603 // A few common patterns: (Foo* means Foo -> FooComplete)
607 // GetBackend* -> InitEntry -> OpenEntry* -> CreateEntry* -> AddToEntry* ->
608 // SendRequest* -> SuccessfulSendRequest -> OverwriteCachedResponse ->
609 // CacheWriteResponse* -> TruncateCachedData* -> TruncateCachedMetadata* ->
610 // PartialHeadersReceived
613 // NetworkRead* -> CacheWriteData*
615 // Cached entry, no validation:
617 // GetBackend* -> InitEntry -> OpenEntry* -> AddToEntry* -> CacheReadResponse*
618 // -> BeginPartialCacheValidation() -> BeginCacheValidation()
623 // Cached entry, validation (304):
625 // GetBackend* -> InitEntry -> OpenEntry* -> AddToEntry* -> CacheReadResponse*
626 // -> BeginPartialCacheValidation() -> BeginCacheValidation() ->
627 // SendRequest* -> SuccessfulSendRequest -> UpdateCachedResponse ->
628 // CacheWriteResponse* -> UpdateCachedResponseComplete ->
629 // OverwriteCachedResponse -> PartialHeadersReceived
634 // Cached entry, validation and replace (200):
636 // GetBackend* -> InitEntry -> OpenEntry* -> AddToEntry* -> CacheReadResponse*
637 // -> BeginPartialCacheValidation() -> BeginCacheValidation() ->
638 // SendRequest* -> SuccessfulSendRequest -> OverwriteCachedResponse ->
639 // CacheWriteResponse* -> DoTruncateCachedData* -> TruncateCachedMetadata* ->
640 // PartialHeadersReceived
643 // NetworkRead* -> CacheWriteData*
645 // Sparse entry, partially cached, byte range request:
647 // GetBackend* -> InitEntry -> OpenEntry* -> AddToEntry* -> CacheReadResponse*
648 // -> BeginPartialCacheValidation() -> CacheQueryData* ->
649 // ValidateEntryHeadersAndContinue() -> StartPartialCacheValidation ->
650 // CompletePartialCacheValidation -> BeginCacheValidation() -> SendRequest* ->
651 // SuccessfulSendRequest -> UpdateCachedResponse -> CacheWriteResponse* ->
652 // UpdateCachedResponseComplete -> OverwriteCachedResponse ->
653 // PartialHeadersReceived
656 // NetworkRead* -> CacheWriteData*
659 // NetworkRead* -> CacheWriteData* -> StartPartialCacheValidation ->
660 // CompletePartialCacheValidation -> CacheReadData* ->
663 // CacheReadData* -> StartPartialCacheValidation ->
664 // CompletePartialCacheValidation -> BeginCacheValidation() -> SendRequest* ->
665 // SuccessfulSendRequest -> UpdateCachedResponse* -> OverwriteCachedResponse
666 // -> PartialHeadersReceived -> NetworkRead* -> CacheWriteData*
668 int HttpCache::Transaction::DoLoop(int result
) {
669 DCHECK(next_state_
!= STATE_NONE
);
673 State state
= next_state_
;
674 next_state_
= STATE_NONE
;
676 case STATE_GET_BACKEND
:
680 case STATE_GET_BACKEND_COMPLETE
:
681 rv
= DoGetBackendComplete(rv
);
683 case STATE_SEND_REQUEST
:
685 rv
= DoSendRequest();
687 case STATE_SEND_REQUEST_COMPLETE
:
688 rv
= DoSendRequestComplete(rv
);
690 case STATE_SUCCESSFUL_SEND_REQUEST
:
692 rv
= DoSuccessfulSendRequest();
694 case STATE_NETWORK_READ
:
696 rv
= DoNetworkRead();
698 case STATE_NETWORK_READ_COMPLETE
:
699 rv
= DoNetworkReadComplete(rv
);
701 case STATE_INIT_ENTRY
:
705 case STATE_OPEN_ENTRY
:
709 case STATE_OPEN_ENTRY_COMPLETE
:
710 rv
= DoOpenEntryComplete(rv
);
712 case STATE_CREATE_ENTRY
:
714 rv
= DoCreateEntry();
716 case STATE_CREATE_ENTRY_COMPLETE
:
717 rv
= DoCreateEntryComplete(rv
);
719 case STATE_DOOM_ENTRY
:
723 case STATE_DOOM_ENTRY_COMPLETE
:
724 rv
= DoDoomEntryComplete(rv
);
726 case STATE_ADD_TO_ENTRY
:
730 case STATE_ADD_TO_ENTRY_COMPLETE
:
731 rv
= DoAddToEntryComplete(rv
);
733 case STATE_START_PARTIAL_CACHE_VALIDATION
:
735 rv
= DoStartPartialCacheValidation();
737 case STATE_COMPLETE_PARTIAL_CACHE_VALIDATION
:
738 rv
= DoCompletePartialCacheValidation(rv
);
740 case STATE_UPDATE_CACHED_RESPONSE
:
742 rv
= DoUpdateCachedResponse();
744 case STATE_UPDATE_CACHED_RESPONSE_COMPLETE
:
745 rv
= DoUpdateCachedResponseComplete(rv
);
747 case STATE_OVERWRITE_CACHED_RESPONSE
:
749 rv
= DoOverwriteCachedResponse();
751 case STATE_TRUNCATE_CACHED_DATA
:
753 rv
= DoTruncateCachedData();
755 case STATE_TRUNCATE_CACHED_DATA_COMPLETE
:
756 rv
= DoTruncateCachedDataComplete(rv
);
758 case STATE_TRUNCATE_CACHED_METADATA
:
760 rv
= DoTruncateCachedMetadata();
762 case STATE_TRUNCATE_CACHED_METADATA_COMPLETE
:
763 rv
= DoTruncateCachedMetadataComplete(rv
);
765 case STATE_PARTIAL_HEADERS_RECEIVED
:
767 rv
= DoPartialHeadersReceived();
769 case STATE_CACHE_READ_RESPONSE
:
771 rv
= DoCacheReadResponse();
773 case STATE_CACHE_READ_RESPONSE_COMPLETE
:
774 rv
= DoCacheReadResponseComplete(rv
);
776 case STATE_CACHE_WRITE_RESPONSE
:
778 rv
= DoCacheWriteResponse();
780 case STATE_CACHE_WRITE_TRUNCATED_RESPONSE
:
782 rv
= DoCacheWriteTruncatedResponse();
784 case STATE_CACHE_WRITE_RESPONSE_COMPLETE
:
785 rv
= DoCacheWriteResponseComplete(rv
);
787 case STATE_CACHE_READ_METADATA
:
789 rv
= DoCacheReadMetadata();
791 case STATE_CACHE_READ_METADATA_COMPLETE
:
792 rv
= DoCacheReadMetadataComplete(rv
);
794 case STATE_CACHE_QUERY_DATA
:
796 rv
= DoCacheQueryData();
798 case STATE_CACHE_QUERY_DATA_COMPLETE
:
799 rv
= DoCacheQueryDataComplete(rv
);
801 case STATE_CACHE_READ_DATA
:
803 rv
= DoCacheReadData();
805 case STATE_CACHE_READ_DATA_COMPLETE
:
806 rv
= DoCacheReadDataComplete(rv
);
808 case STATE_CACHE_WRITE_DATA
:
809 rv
= DoCacheWriteData(rv
);
811 case STATE_CACHE_WRITE_DATA_COMPLETE
:
812 rv
= DoCacheWriteDataComplete(rv
);
815 NOTREACHED() << "bad state";
819 } while (rv
!= ERR_IO_PENDING
&& next_state_
!= STATE_NONE
);
821 if (rv
!= ERR_IO_PENDING
)
827 int HttpCache::Transaction::DoGetBackend() {
828 cache_pending_
= true;
829 next_state_
= STATE_GET_BACKEND_COMPLETE
;
830 net_log_
.BeginEvent(NetLog::TYPE_HTTP_CACHE_GET_BACKEND
);
831 return cache_
->GetBackendForTransaction(this);
834 int HttpCache::Transaction::DoGetBackendComplete(int result
) {
835 DCHECK(result
== OK
|| result
== ERR_FAILED
);
836 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_HTTP_CACHE_GET_BACKEND
,
838 cache_pending_
= false;
840 if (!ShouldPassThrough()) {
841 cache_key_
= cache_
->GenerateCacheKey(request_
);
843 // Requested cache access mode.
844 if (effective_load_flags_
& LOAD_ONLY_FROM_CACHE
) {
846 } else if (effective_load_flags_
& LOAD_BYPASS_CACHE
) {
852 // Downgrade to UPDATE if the request has been externally conditionalized.
853 if (external_validation_
.initialized
) {
855 // Strip off the READ_DATA bit (and maybe add back a READ_META bit
856 // in case READ was off).
864 // Use PUT and DELETE only to invalidate existing stored entries.
865 if ((request_
->method
== "PUT" || request_
->method
== "DELETE") &&
866 mode_
!= READ_WRITE
&& mode_
!= WRITE
) {
870 // If must use cache, then we must fail. This can happen for back/forward
871 // navigations to a page generated via a form post.
872 if (!(mode_
& READ
) && effective_load_flags_
& LOAD_ONLY_FROM_CACHE
)
873 return ERR_CACHE_MISS
;
876 if (partial_
.get()) {
877 partial_
->RestoreHeaders(&custom_request_
->extra_headers
);
880 next_state_
= STATE_SEND_REQUEST
;
882 next_state_
= STATE_INIT_ENTRY
;
885 // This is only set if we have something to do with the response.
886 range_requested_
= (partial_
.get() != NULL
);
891 int HttpCache::Transaction::DoSendRequest() {
892 DCHECK(mode_
& WRITE
|| mode_
== NONE
);
893 DCHECK(!network_trans_
.get());
895 send_request_since_
= TimeTicks::Now();
897 // Create a network transaction.
898 int rv
= cache_
->network_layer_
->CreateTransaction(priority_
,
902 network_trans_
->SetBeforeNetworkStartCallback(before_network_start_callback_
);
903 network_trans_
->SetBeforeProxyHeadersSentCallback(
904 before_proxy_headers_sent_callback_
);
906 // Old load timing information, if any, is now obsolete.
907 old_network_trans_load_timing_
.reset();
909 if (websocket_handshake_stream_base_create_helper_
)
910 network_trans_
->SetWebSocketHandshakeStreamCreateHelper(
911 websocket_handshake_stream_base_create_helper_
);
913 next_state_
= STATE_SEND_REQUEST_COMPLETE
;
914 rv
= network_trans_
->Start(request_
, io_callback_
, net_log_
);
918 int HttpCache::Transaction::DoSendRequestComplete(int result
) {
920 return ERR_UNEXPECTED
;
922 // If requested, and we have a readable cache entry, and we have
923 // an error indicating that we're offline as opposed to in contact
924 // with a bad server, read from cache anyway.
925 if (IsOfflineError(result
)) {
926 if (mode_
== READ_WRITE
&& entry_
&& !partial_
) {
927 RecordOfflineStatus(effective_load_flags_
,
928 OFFLINE_STATUS_DATA_AVAILABLE_OFFLINE
);
929 if (effective_load_flags_
& LOAD_FROM_CACHE_IF_OFFLINE
) {
930 UpdateTransactionPattern(PATTERN_NOT_COVERED
);
931 response_
.server_data_unavailable
= true;
932 return SetupEntryForRead();
935 RecordOfflineStatus(effective_load_flags_
,
936 OFFLINE_STATUS_DATA_UNAVAILABLE_OFFLINE
);
939 RecordOfflineStatus(effective_load_flags_
,
940 (result
== OK
? OFFLINE_STATUS_NETWORK_SUCCEEDED
:
941 OFFLINE_STATUS_NETWORK_FAILED
));
944 // If we tried to conditionalize the request and failed, we know
945 // we won't be reading from the cache after this point.
946 if (couldnt_conditionalize_request_
)
950 next_state_
= STATE_SUCCESSFUL_SEND_REQUEST
;
954 // Do not record requests that have network errors or restarts.
955 UpdateTransactionPattern(PATTERN_NOT_COVERED
);
956 if (IsCertificateError(result
)) {
957 const HttpResponseInfo
* response
= network_trans_
->GetResponseInfo();
958 // If we get a certificate error, then there is a certificate in ssl_info,
959 // so GetResponseInfo() should never return NULL here.
961 response_
.ssl_info
= response
->ssl_info
;
962 } else if (result
== ERR_SSL_CLIENT_AUTH_CERT_NEEDED
) {
963 const HttpResponseInfo
* response
= network_trans_
->GetResponseInfo();
965 response_
.cert_request_info
= response
->cert_request_info
;
966 } else if (response_
.was_cached
) {
967 DoneWritingToEntry(true);
972 // We received the response headers and there is no error.
973 int HttpCache::Transaction::DoSuccessfulSendRequest() {
974 DCHECK(!new_response_
);
975 const HttpResponseInfo
* new_response
= network_trans_
->GetResponseInfo();
976 bool authentication_failure
= false;
978 if (new_response
->headers
->response_code() == 401 ||
979 new_response
->headers
->response_code() == 407) {
980 auth_response_
= *new_response
;
984 // We initiated a second request the caller doesn't know about. We should be
985 // able to authenticate this request because we should have authenticated
986 // this URL moments ago.
987 if (IsReadyToRestartForAuth()) {
988 DCHECK(!response_
.auth_challenge
.get());
989 next_state_
= STATE_SEND_REQUEST_COMPLETE
;
990 // In theory we should check to see if there are new cookies, but there
991 // is no way to do that from here.
992 return network_trans_
->RestartWithAuth(AuthCredentials(), io_callback_
);
995 // We have to perform cleanup at this point so that at least the next
996 // request can succeed.
997 authentication_failure
= true;
999 DoomPartialEntry(false);
1004 new_response_
= new_response
;
1005 if (authentication_failure
||
1006 (!ValidatePartialResponse() && !auth_response_
.headers
.get())) {
1007 // Something went wrong with this request and we have to restart it.
1008 // If we have an authentication response, we are exposed to weird things
1009 // hapenning if the user cancels the authentication before we receive
1010 // the new response.
1011 UpdateTransactionPattern(PATTERN_NOT_COVERED
);
1012 response_
= HttpResponseInfo();
1013 ResetNetworkTransaction();
1014 new_response_
= NULL
;
1015 next_state_
= STATE_SEND_REQUEST
;
1019 if (handling_206_
&& mode_
== READ_WRITE
&& !truncated_
&& !is_sparse_
) {
1020 // We have stored the full entry, but it changed and the server is
1021 // sending a range. We have to delete the old entry.
1022 UpdateTransactionPattern(PATTERN_NOT_COVERED
);
1023 DoneWritingToEntry(false);
1026 if (mode_
== WRITE
&&
1027 transaction_pattern_
!= PATTERN_ENTRY_CANT_CONDITIONALIZE
) {
1028 UpdateTransactionPattern(PATTERN_ENTRY_NOT_CACHED
);
1031 if (mode_
== WRITE
&&
1032 (request_
->method
== "PUT" || request_
->method
== "DELETE")) {
1033 if (NonErrorResponse(new_response
->headers
->response_code())) {
1034 int ret
= cache_
->DoomEntry(cache_key_
, NULL
);
1037 cache_
->DoneWritingToEntry(entry_
, true);
1042 if (request_
->method
== "POST" &&
1043 NonErrorResponse(new_response
->headers
->response_code())) {
1044 cache_
->DoomMainEntryForUrl(request_
->url
);
1047 RecordVaryHeaderHistogram(new_response
);
1048 RecordNoStoreHeaderHistogram(request_
->load_flags
, new_response
);
1050 if (new_response_
->headers
->response_code() == 416 &&
1051 (request_
->method
== "GET" || request_
->method
== "POST")) {
1052 // If there is an ective entry it may be destroyed with this transaction.
1053 response_
= *new_response_
;
1057 // Are we expecting a response to a conditional query?
1058 if (mode_
== READ_WRITE
|| mode_
== UPDATE
) {
1059 if (new_response
->headers
->response_code() == 304 || handling_206_
) {
1060 UpdateTransactionPattern(PATTERN_ENTRY_VALIDATED
);
1061 next_state_
= STATE_UPDATE_CACHED_RESPONSE
;
1064 UpdateTransactionPattern(PATTERN_ENTRY_UPDATED
);
1068 next_state_
= STATE_OVERWRITE_CACHED_RESPONSE
;
1072 int HttpCache::Transaction::DoNetworkRead() {
1073 next_state_
= STATE_NETWORK_READ_COMPLETE
;
1074 return network_trans_
->Read(read_buf_
.get(), io_buf_len_
, io_callback_
);
1077 int HttpCache::Transaction::DoNetworkReadComplete(int result
) {
1078 DCHECK(mode_
& WRITE
|| mode_
== NONE
);
1081 return ERR_UNEXPECTED
;
1083 // If there is an error or we aren't saving the data, we are done; just wait
1084 // until the destructor runs to see if we can keep the data.
1085 if (mode_
== NONE
|| result
< 0)
1088 next_state_
= STATE_CACHE_WRITE_DATA
;
1092 int HttpCache::Transaction::DoInitEntry() {
1093 DCHECK(!new_entry_
);
1096 return ERR_UNEXPECTED
;
1098 if (mode_
== WRITE
) {
1099 next_state_
= STATE_DOOM_ENTRY
;
1103 next_state_
= STATE_OPEN_ENTRY
;
1107 int HttpCache::Transaction::DoOpenEntry() {
1108 DCHECK(!new_entry_
);
1109 next_state_
= STATE_OPEN_ENTRY_COMPLETE
;
1110 cache_pending_
= true;
1111 net_log_
.BeginEvent(NetLog::TYPE_HTTP_CACHE_OPEN_ENTRY
);
1112 first_cache_access_since_
= TimeTicks::Now();
1113 return cache_
->OpenEntry(cache_key_
, &new_entry_
, this);
1116 int HttpCache::Transaction::DoOpenEntryComplete(int result
) {
1117 // It is important that we go to STATE_ADD_TO_ENTRY whenever the result is
1118 // OK, otherwise the cache will end up with an active entry without any
1119 // transaction attached.
1120 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_HTTP_CACHE_OPEN_ENTRY
, result
);
1121 cache_pending_
= false;
1123 next_state_
= STATE_ADD_TO_ENTRY
;
1127 if (result
== ERR_CACHE_RACE
) {
1128 next_state_
= STATE_INIT_ENTRY
;
1132 if (request_
->method
== "PUT" || request_
->method
== "DELETE") {
1133 DCHECK(mode_
== READ_WRITE
|| mode_
== WRITE
);
1135 next_state_
= STATE_SEND_REQUEST
;
1139 if (mode_
== READ_WRITE
) {
1141 next_state_
= STATE_CREATE_ENTRY
;
1144 if (mode_
== UPDATE
) {
1145 // There is no cache entry to update; proceed without caching.
1147 next_state_
= STATE_SEND_REQUEST
;
1150 if (cache_
->mode() == PLAYBACK
)
1151 DVLOG(1) << "Playback Cache Miss: " << request_
->url
;
1153 // The entry does not exist, and we are not permitted to create a new entry,
1155 return ERR_CACHE_MISS
;
1158 int HttpCache::Transaction::DoCreateEntry() {
1159 DCHECK(!new_entry_
);
1160 next_state_
= STATE_CREATE_ENTRY_COMPLETE
;
1161 cache_pending_
= true;
1162 net_log_
.BeginEvent(NetLog::TYPE_HTTP_CACHE_CREATE_ENTRY
);
1163 return cache_
->CreateEntry(cache_key_
, &new_entry_
, this);
1166 int HttpCache::Transaction::DoCreateEntryComplete(int result
) {
1167 // It is important that we go to STATE_ADD_TO_ENTRY whenever the result is
1168 // OK, otherwise the cache will end up with an active entry without any
1169 // transaction attached.
1170 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_HTTP_CACHE_CREATE_ENTRY
,
1172 cache_pending_
= false;
1173 next_state_
= STATE_ADD_TO_ENTRY
;
1175 if (result
== ERR_CACHE_RACE
) {
1176 next_state_
= STATE_INIT_ENTRY
;
1181 UMA_HISTOGRAM_BOOLEAN("HttpCache.OpenToCreateRace", false);
1183 UMA_HISTOGRAM_BOOLEAN("HttpCache.OpenToCreateRace", true);
1184 // We have a race here: Maybe we failed to open the entry and decided to
1185 // create one, but by the time we called create, another transaction already
1186 // created the entry. If we want to eliminate this issue, we need an atomic
1187 // OpenOrCreate() method exposed by the disk cache.
1188 DLOG(WARNING
) << "Unable to create cache entry";
1191 partial_
->RestoreHeaders(&custom_request_
->extra_headers
);
1192 next_state_
= STATE_SEND_REQUEST
;
1197 int HttpCache::Transaction::DoDoomEntry() {
1198 next_state_
= STATE_DOOM_ENTRY_COMPLETE
;
1199 cache_pending_
= true;
1200 if (first_cache_access_since_
.is_null())
1201 first_cache_access_since_
= TimeTicks::Now();
1202 net_log_
.BeginEvent(NetLog::TYPE_HTTP_CACHE_DOOM_ENTRY
);
1203 return cache_
->DoomEntry(cache_key_
, this);
1206 int HttpCache::Transaction::DoDoomEntryComplete(int result
) {
1207 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_HTTP_CACHE_DOOM_ENTRY
, result
);
1208 next_state_
= STATE_CREATE_ENTRY
;
1209 cache_pending_
= false;
1210 if (result
== ERR_CACHE_RACE
)
1211 next_state_
= STATE_INIT_ENTRY
;
1215 int HttpCache::Transaction::DoAddToEntry() {
1217 cache_pending_
= true;
1218 next_state_
= STATE_ADD_TO_ENTRY_COMPLETE
;
1219 net_log_
.BeginEvent(NetLog::TYPE_HTTP_CACHE_ADD_TO_ENTRY
);
1220 DCHECK(entry_lock_waiting_since_
.is_null());
1221 entry_lock_waiting_since_
= TimeTicks::Now();
1222 int rv
= cache_
->AddTransactionToEntry(new_entry_
, this);
1223 if (rv
== ERR_IO_PENDING
) {
1224 if (bypass_lock_for_test_
) {
1225 OnAddToEntryTimeout(entry_lock_waiting_since_
);
1227 const int kTimeoutSeconds
= 20;
1228 base::MessageLoop::current()->PostDelayedTask(
1230 base::Bind(&HttpCache::Transaction::OnAddToEntryTimeout
,
1231 weak_factory_
.GetWeakPtr(), entry_lock_waiting_since_
),
1232 TimeDelta::FromSeconds(kTimeoutSeconds
));
1238 int HttpCache::Transaction::DoAddToEntryComplete(int result
) {
1239 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_HTTP_CACHE_ADD_TO_ENTRY
,
1241 const TimeDelta entry_lock_wait
=
1242 TimeTicks::Now() - entry_lock_waiting_since_
;
1243 UMA_HISTOGRAM_TIMES("HttpCache.EntryLockWait", entry_lock_wait
);
1245 entry_lock_waiting_since_
= TimeTicks();
1247 cache_pending_
= false;
1250 entry_
= new_entry_
;
1252 // If there is a failure, the cache should have taken care of new_entry_.
1255 if (result
== ERR_CACHE_RACE
) {
1256 next_state_
= STATE_INIT_ENTRY
;
1260 if (result
== ERR_CACHE_LOCK_TIMEOUT
) {
1261 // The cache is busy, bypass it for this transaction.
1263 next_state_
= STATE_SEND_REQUEST
;
1265 partial_
->RestoreHeaders(&custom_request_
->extra_headers
);
1276 if (mode_
== WRITE
) {
1278 partial_
->RestoreHeaders(&custom_request_
->extra_headers
);
1279 next_state_
= STATE_SEND_REQUEST
;
1281 // We have to read the headers from the cached entry.
1282 DCHECK(mode_
& READ_META
);
1283 next_state_
= STATE_CACHE_READ_RESPONSE
;
1288 // We may end up here multiple times for a given request.
1289 int HttpCache::Transaction::DoStartPartialCacheValidation() {
1293 next_state_
= STATE_COMPLETE_PARTIAL_CACHE_VALIDATION
;
1294 return partial_
->ShouldValidateCache(entry_
->disk_entry
, io_callback_
);
1297 int HttpCache::Transaction::DoCompletePartialCacheValidation(int result
) {
1299 // This is the end of the request.
1300 if (mode_
& WRITE
) {
1301 DoneWritingToEntry(true);
1303 cache_
->DoneReadingFromEntry(entry_
, this);
1312 partial_
->PrepareCacheValidation(entry_
->disk_entry
,
1313 &custom_request_
->extra_headers
);
1315 if (reading_
&& partial_
->IsCurrentRangeCached()) {
1316 next_state_
= STATE_CACHE_READ_DATA
;
1320 return BeginCacheValidation();
1323 // We received 304 or 206 and we want to update the cached response headers.
1324 int HttpCache::Transaction::DoUpdateCachedResponse() {
1325 next_state_
= STATE_UPDATE_CACHED_RESPONSE_COMPLETE
;
1327 // Update cached response based on headers in new_response.
1328 // TODO(wtc): should we update cached certificate (response_.ssl_info), too?
1329 response_
.headers
->Update(*new_response_
->headers
.get());
1330 response_
.response_time
= new_response_
->response_time
;
1331 response_
.request_time
= new_response_
->request_time
;
1332 response_
.network_accessed
= new_response_
->network_accessed
;
1334 if (response_
.headers
->HasHeaderValue("cache-control", "no-store")) {
1335 if (!entry_
->doomed
) {
1336 int ret
= cache_
->DoomEntry(cache_key_
, NULL
);
1340 // If we are already reading, we already updated the headers for this
1341 // request; doing it again will change Content-Length.
1343 target_state_
= STATE_UPDATE_CACHED_RESPONSE_COMPLETE
;
1344 next_state_
= STATE_CACHE_WRITE_RESPONSE
;
1351 int HttpCache::Transaction::DoUpdateCachedResponseComplete(int result
) {
1352 if (mode_
== UPDATE
) {
1353 DCHECK(!handling_206_
);
1354 // We got a "not modified" response and already updated the corresponding
1355 // cache entry above.
1357 // By closing the cached entry now, we make sure that the 304 rather than
1358 // the cached 200 response, is what will be returned to the user.
1359 DoneWritingToEntry(true);
1360 } else if (entry_
&& !handling_206_
) {
1361 DCHECK_EQ(READ_WRITE
, mode_
);
1362 if (!partial_
.get() || partial_
->IsLastRange()) {
1363 cache_
->ConvertWriterToReader(entry_
);
1366 // We no longer need the network transaction, so destroy it.
1367 final_upload_progress_
= network_trans_
->GetUploadProgress();
1368 ResetNetworkTransaction();
1369 } else if (entry_
&& handling_206_
&& truncated_
&&
1370 partial_
->initial_validation()) {
1371 // We just finished the validation of a truncated entry, and the server
1372 // is willing to resume the operation. Now we go back and start serving
1373 // the first part to the user.
1374 ResetNetworkTransaction();
1375 new_response_
= NULL
;
1376 next_state_
= STATE_START_PARTIAL_CACHE_VALIDATION
;
1377 partial_
->SetRangeToStartDownload();
1380 next_state_
= STATE_OVERWRITE_CACHED_RESPONSE
;
1384 int HttpCache::Transaction::DoOverwriteCachedResponse() {
1386 next_state_
= STATE_PARTIAL_HEADERS_RECEIVED
;
1390 // We change the value of Content-Length for partial content.
1391 if (handling_206_
&& partial_
.get())
1392 partial_
->FixContentLength(new_response_
->headers
.get());
1394 response_
= *new_response_
;
1396 if (handling_206_
&& !CanResume(false)) {
1397 // There is no point in storing this resource because it will never be used.
1398 DoneWritingToEntry(false);
1400 partial_
->FixResponseHeaders(response_
.headers
.get(), true);
1401 next_state_
= STATE_PARTIAL_HEADERS_RECEIVED
;
1405 target_state_
= STATE_TRUNCATE_CACHED_DATA
;
1406 next_state_
= truncated_
? STATE_CACHE_WRITE_TRUNCATED_RESPONSE
:
1407 STATE_CACHE_WRITE_RESPONSE
;
1411 int HttpCache::Transaction::DoTruncateCachedData() {
1412 next_state_
= STATE_TRUNCATE_CACHED_DATA_COMPLETE
;
1415 if (net_log_
.IsLogging())
1416 net_log_
.BeginEvent(NetLog::TYPE_HTTP_CACHE_WRITE_DATA
);
1417 // Truncate the stream.
1418 return WriteToEntry(kResponseContentIndex
, 0, NULL
, 0, io_callback_
);
1421 int HttpCache::Transaction::DoTruncateCachedDataComplete(int result
) {
1423 if (net_log_
.IsLogging()) {
1424 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_HTTP_CACHE_WRITE_DATA
,
1429 next_state_
= STATE_TRUNCATE_CACHED_METADATA
;
1433 int HttpCache::Transaction::DoTruncateCachedMetadata() {
1434 next_state_
= STATE_TRUNCATE_CACHED_METADATA_COMPLETE
;
1438 if (net_log_
.IsLogging())
1439 net_log_
.BeginEvent(NetLog::TYPE_HTTP_CACHE_WRITE_INFO
);
1440 return WriteToEntry(kMetadataIndex
, 0, NULL
, 0, io_callback_
);
1443 int HttpCache::Transaction::DoTruncateCachedMetadataComplete(int result
) {
1445 if (net_log_
.IsLogging()) {
1446 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_HTTP_CACHE_WRITE_INFO
,
1451 next_state_
= STATE_PARTIAL_HEADERS_RECEIVED
;
1455 int HttpCache::Transaction::DoPartialHeadersReceived() {
1456 new_response_
= NULL
;
1457 if (entry_
&& !partial_
.get() &&
1458 entry_
->disk_entry
->GetDataSize(kMetadataIndex
))
1459 next_state_
= STATE_CACHE_READ_METADATA
;
1461 if (!partial_
.get())
1465 if (network_trans_
.get()) {
1466 next_state_
= STATE_NETWORK_READ
;
1468 next_state_
= STATE_CACHE_READ_DATA
;
1470 } else if (mode_
!= NONE
) {
1471 // We are about to return the headers for a byte-range request to the user,
1472 // so let's fix them.
1473 partial_
->FixResponseHeaders(response_
.headers
.get(), true);
1478 int HttpCache::Transaction::DoCacheReadResponse() {
1480 next_state_
= STATE_CACHE_READ_RESPONSE_COMPLETE
;
1482 io_buf_len_
= entry_
->disk_entry
->GetDataSize(kResponseInfoIndex
);
1483 read_buf_
= new IOBuffer(io_buf_len_
);
1485 net_log_
.BeginEvent(NetLog::TYPE_HTTP_CACHE_READ_INFO
);
1486 return entry_
->disk_entry
->ReadData(kResponseInfoIndex
, 0, read_buf_
.get(),
1487 io_buf_len_
, io_callback_
);
1490 int HttpCache::Transaction::DoCacheReadResponseComplete(int result
) {
1491 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_HTTP_CACHE_READ_INFO
, result
);
1492 if (result
!= io_buf_len_
||
1493 !HttpCache::ParseResponseInfo(read_buf_
->data(), io_buf_len_
,
1494 &response_
, &truncated_
)) {
1495 return OnCacheReadError(result
, true);
1498 // Some resources may have slipped in as truncated when they're not.
1499 int current_size
= entry_
->disk_entry
->GetDataSize(kResponseContentIndex
);
1500 if (response_
.headers
->GetContentLength() == current_size
)
1503 // We now have access to the cache entry.
1505 // o if we are a reader for the transaction, then we can start reading the
1508 // o if we can read or write, then we should check if the cache entry needs
1509 // to be validated and then issue a network request if needed or just read
1510 // from the cache if the cache entry is already valid.
1512 // o if we are set to UPDATE, then we are handling an externally
1513 // conditionalized request (if-modified-since / if-none-match). We check
1514 // if the request headers define a validation request.
1518 UpdateTransactionPattern(PATTERN_ENTRY_USED
);
1519 result
= BeginCacheRead();
1522 result
= BeginPartialCacheValidation();
1525 result
= BeginExternallyConditionalizedRequest();
1530 result
= ERR_FAILED
;
1535 int HttpCache::Transaction::DoCacheWriteResponse() {
1537 if (net_log_
.IsLogging())
1538 net_log_
.BeginEvent(NetLog::TYPE_HTTP_CACHE_WRITE_INFO
);
1540 return WriteResponseInfoToEntry(false);
1543 int HttpCache::Transaction::DoCacheWriteTruncatedResponse() {
1545 if (net_log_
.IsLogging())
1546 net_log_
.BeginEvent(NetLog::TYPE_HTTP_CACHE_WRITE_INFO
);
1548 return WriteResponseInfoToEntry(true);
1551 int HttpCache::Transaction::DoCacheWriteResponseComplete(int result
) {
1552 next_state_
= target_state_
;
1553 target_state_
= STATE_NONE
;
1556 if (net_log_
.IsLogging()) {
1557 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_HTTP_CACHE_WRITE_INFO
,
1561 // Balance the AddRef from WriteResponseInfoToEntry.
1562 if (result
!= io_buf_len_
) {
1563 DLOG(ERROR
) << "failed to write response info to cache";
1564 DoneWritingToEntry(false);
1569 int HttpCache::Transaction::DoCacheReadMetadata() {
1571 DCHECK(!response_
.metadata
.get());
1572 next_state_
= STATE_CACHE_READ_METADATA_COMPLETE
;
1574 response_
.metadata
=
1575 new IOBufferWithSize(entry_
->disk_entry
->GetDataSize(kMetadataIndex
));
1577 net_log_
.BeginEvent(NetLog::TYPE_HTTP_CACHE_READ_INFO
);
1578 return entry_
->disk_entry
->ReadData(kMetadataIndex
, 0,
1579 response_
.metadata
.get(),
1580 response_
.metadata
->size(),
1584 int HttpCache::Transaction::DoCacheReadMetadataComplete(int result
) {
1585 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_HTTP_CACHE_READ_INFO
, result
);
1586 if (result
!= response_
.metadata
->size())
1587 return OnCacheReadError(result
, false);
1591 int HttpCache::Transaction::DoCacheQueryData() {
1592 next_state_
= STATE_CACHE_QUERY_DATA_COMPLETE
;
1593 return entry_
->disk_entry
->ReadyForSparseIO(io_callback_
);
1596 int HttpCache::Transaction::DoCacheQueryDataComplete(int result
) {
1597 if (result
== ERR_NOT_IMPLEMENTED
) {
1598 // Restart the request overwriting the cache entry.
1599 // TODO(pasko): remove this workaround as soon as the SimpleBackendImpl
1600 // supports Sparse IO.
1601 return DoRestartPartialRequest();
1603 DCHECK_EQ(OK
, result
);
1605 return ERR_UNEXPECTED
;
1607 return ValidateEntryHeadersAndContinue();
1610 int HttpCache::Transaction::DoCacheReadData() {
1612 next_state_
= STATE_CACHE_READ_DATA_COMPLETE
;
1614 if (net_log_
.IsLogging())
1615 net_log_
.BeginEvent(NetLog::TYPE_HTTP_CACHE_READ_DATA
);
1616 if (partial_
.get()) {
1617 return partial_
->CacheRead(entry_
->disk_entry
, read_buf_
.get(), io_buf_len_
,
1621 return entry_
->disk_entry
->ReadData(kResponseContentIndex
, read_offset_
,
1622 read_buf_
.get(), io_buf_len_
,
1626 int HttpCache::Transaction::DoCacheReadDataComplete(int result
) {
1627 if (net_log_
.IsLogging()) {
1628 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_HTTP_CACHE_READ_DATA
,
1633 return ERR_UNEXPECTED
;
1635 if (partial_
.get()) {
1636 // Partial requests are confusing to report in histograms because they may
1637 // have multiple underlying requests.
1638 UpdateTransactionPattern(PATTERN_NOT_COVERED
);
1639 return DoPartialCacheReadCompleted(result
);
1643 read_offset_
+= result
;
1644 } else if (result
== 0) { // End of file.
1646 cache_
->DoneReadingFromEntry(entry_
, this);
1649 return OnCacheReadError(result
, false);
1654 int HttpCache::Transaction::DoCacheWriteData(int num_bytes
) {
1655 next_state_
= STATE_CACHE_WRITE_DATA_COMPLETE
;
1656 write_len_
= num_bytes
;
1658 if (net_log_
.IsLogging())
1659 net_log_
.BeginEvent(NetLog::TYPE_HTTP_CACHE_WRITE_DATA
);
1662 return AppendResponseDataToEntry(read_buf_
.get(), num_bytes
, io_callback_
);
1665 int HttpCache::Transaction::DoCacheWriteDataComplete(int result
) {
1667 if (net_log_
.IsLogging()) {
1668 net_log_
.EndEventWithNetErrorCode(NetLog::TYPE_HTTP_CACHE_WRITE_DATA
,
1672 // Balance the AddRef from DoCacheWriteData.
1674 return ERR_UNEXPECTED
;
1676 if (result
!= write_len_
) {
1677 DLOG(ERROR
) << "failed to write response data to cache";
1678 DoneWritingToEntry(false);
1680 // We want to ignore errors writing to disk and just keep reading from
1682 result
= write_len_
;
1683 } else if (!done_reading_
&& entry_
) {
1684 int current_size
= entry_
->disk_entry
->GetDataSize(kResponseContentIndex
);
1685 int64 body_size
= response_
.headers
->GetContentLength();
1686 if (body_size
>= 0 && body_size
<= current_size
)
1687 done_reading_
= true;
1690 if (partial_
.get()) {
1691 // This may be the last request.
1692 if (!(result
== 0 && !truncated_
&&
1693 (partial_
->IsLastRange() || mode_
== WRITE
)))
1694 return DoPartialNetworkReadCompleted(result
);
1698 // End of file. This may be the result of a connection problem so see if we
1699 // have to keep the entry around to be flagged as truncated later on.
1700 if (done_reading_
|| !entry_
|| partial_
.get() ||
1701 response_
.headers
->GetContentLength() <= 0)
1702 DoneWritingToEntry(true);
1708 //-----------------------------------------------------------------------------
1710 void HttpCache::Transaction::SetRequest(const BoundNetLog
& net_log
,
1711 const HttpRequestInfo
* request
) {
1714 effective_load_flags_
= request_
->load_flags
;
1716 switch (cache_
->mode()) {
1720 // When in record mode, we want to NEVER load from the cache.
1721 // The reason for this is beacuse we save the Set-Cookie headers
1722 // (intentionally). If we read from the cache, we replay them
1724 effective_load_flags_
|= LOAD_BYPASS_CACHE
;
1727 // When in playback mode, we want to load exclusively from the cache.
1728 effective_load_flags_
|= LOAD_ONLY_FROM_CACHE
;
1731 effective_load_flags_
|= LOAD_DISABLE_CACHE
;
1735 // Some headers imply load flags. The order here is significant.
1737 // LOAD_DISABLE_CACHE : no cache read or write
1738 // LOAD_BYPASS_CACHE : no cache read
1739 // LOAD_VALIDATE_CACHE : no cache read unless validation
1741 // The former modes trump latter modes, so if we find a matching header we
1742 // can stop iterating kSpecialHeaders.
1744 static const struct {
1745 const HeaderNameAndValue
* search
;
1747 } kSpecialHeaders
[] = {
1748 { kPassThroughHeaders
, LOAD_DISABLE_CACHE
},
1749 { kForceFetchHeaders
, LOAD_BYPASS_CACHE
},
1750 { kForceValidateHeaders
, LOAD_VALIDATE_CACHE
},
1753 bool range_found
= false;
1754 bool external_validation_error
= false;
1756 if (request_
->extra_headers
.HasHeader(HttpRequestHeaders::kRange
))
1759 for (size_t i
= 0; i
< ARRAYSIZE_UNSAFE(kSpecialHeaders
); ++i
) {
1760 if (HeaderMatches(request_
->extra_headers
, kSpecialHeaders
[i
].search
)) {
1761 effective_load_flags_
|= kSpecialHeaders
[i
].load_flag
;
1766 // Check for conditionalization headers which may correspond with a
1767 // cache validation request.
1768 for (size_t i
= 0; i
< arraysize(kValidationHeaders
); ++i
) {
1769 const ValidationHeaderInfo
& info
= kValidationHeaders
[i
];
1770 std::string validation_value
;
1771 if (request_
->extra_headers
.GetHeader(
1772 info
.request_header_name
, &validation_value
)) {
1773 if (!external_validation_
.values
[i
].empty() ||
1774 validation_value
.empty()) {
1775 external_validation_error
= true;
1777 external_validation_
.values
[i
] = validation_value
;
1778 external_validation_
.initialized
= true;
1782 // We don't support ranges and validation headers.
1783 if (range_found
&& external_validation_
.initialized
) {
1784 LOG(WARNING
) << "Byte ranges AND validation headers found.";
1785 effective_load_flags_
|= LOAD_DISABLE_CACHE
;
1788 // If there is more than one validation header, we can't treat this request as
1789 // a cache validation, since we don't know for sure which header the server
1790 // will give us a response for (and they could be contradictory).
1791 if (external_validation_error
) {
1792 LOG(WARNING
) << "Multiple or malformed validation headers found.";
1793 effective_load_flags_
|= LOAD_DISABLE_CACHE
;
1796 if (range_found
&& !(effective_load_flags_
& LOAD_DISABLE_CACHE
)) {
1797 UpdateTransactionPattern(PATTERN_NOT_COVERED
);
1798 partial_
.reset(new PartialData
);
1799 if (request_
->method
== "GET" && partial_
->Init(request_
->extra_headers
)) {
1800 // We will be modifying the actual range requested to the server, so
1801 // let's remove the header here.
1802 custom_request_
.reset(new HttpRequestInfo(*request_
));
1803 custom_request_
->extra_headers
.RemoveHeader(HttpRequestHeaders::kRange
);
1804 request_
= custom_request_
.get();
1805 partial_
->SetHeaders(custom_request_
->extra_headers
);
1807 // The range is invalid or we cannot handle it properly.
1808 VLOG(1) << "Invalid byte range found.";
1809 effective_load_flags_
|= LOAD_DISABLE_CACHE
;
1810 partial_
.reset(NULL
);
1815 bool HttpCache::Transaction::ShouldPassThrough() {
1816 // We may have a null disk_cache if there is an error we cannot recover from,
1817 // like not enough disk space, or sharing violations.
1818 if (!cache_
->disk_cache_
.get())
1821 // When using the record/playback modes, we always use the cache
1822 // and we never pass through.
1823 if (cache_
->mode() == RECORD
|| cache_
->mode() == PLAYBACK
)
1826 if (effective_load_flags_
& LOAD_DISABLE_CACHE
)
1829 if (request_
->method
== "GET")
1832 if (request_
->method
== "POST" && request_
->upload_data_stream
&&
1833 request_
->upload_data_stream
->identifier()) {
1837 if (request_
->method
== "PUT" && request_
->upload_data_stream
)
1840 if (request_
->method
== "DELETE")
1843 // TODO(darin): add support for caching HEAD responses
1847 int HttpCache::Transaction::BeginCacheRead() {
1848 // We don't support any combination of LOAD_ONLY_FROM_CACHE and byte ranges.
1849 if (response_
.headers
->response_code() == 206 || partial_
.get()) {
1851 return ERR_CACHE_MISS
;
1854 // We don't have the whole resource.
1856 return ERR_CACHE_MISS
;
1858 if (entry_
->disk_entry
->GetDataSize(kMetadataIndex
))
1859 next_state_
= STATE_CACHE_READ_METADATA
;
1864 int HttpCache::Transaction::BeginCacheValidation() {
1865 DCHECK(mode_
== READ_WRITE
);
1867 bool skip_validation
= !RequiresValidation();
1870 // Truncated entries can cause partial gets, so we shouldn't record this
1871 // load in histograms.
1872 UpdateTransactionPattern(PATTERN_NOT_COVERED
);
1873 skip_validation
= !partial_
->initial_validation();
1876 if (partial_
.get() && (is_sparse_
|| truncated_
) &&
1877 (!partial_
->IsCurrentRangeCached() || invalid_range_
)) {
1878 // Force revalidation for sparse or truncated entries. Note that we don't
1879 // want to ignore the regular validation logic just because a byte range was
1880 // part of the request.
1881 skip_validation
= false;
1884 if (skip_validation
) {
1885 UpdateTransactionPattern(PATTERN_ENTRY_USED
);
1886 RecordOfflineStatus(effective_load_flags_
, OFFLINE_STATUS_FRESH_CACHE
);
1887 return SetupEntryForRead();
1889 // Make the network request conditional, to see if we may reuse our cached
1890 // response. If we cannot do so, then we just resort to a normal fetch.
1891 // Our mode remains READ_WRITE for a conditional request. Even if the
1892 // conditionalization fails, we don't switch to WRITE mode until we
1893 // know we won't be falling back to using the cache entry in the
1894 // LOAD_FROM_CACHE_IF_OFFLINE case.
1895 if (!ConditionalizeRequest()) {
1896 couldnt_conditionalize_request_
= true;
1897 UpdateTransactionPattern(PATTERN_ENTRY_CANT_CONDITIONALIZE
);
1899 return DoRestartPartialRequest();
1901 DCHECK_NE(206, response_
.headers
->response_code());
1903 next_state_
= STATE_SEND_REQUEST
;
1908 int HttpCache::Transaction::BeginPartialCacheValidation() {
1909 DCHECK(mode_
== READ_WRITE
);
1911 if (response_
.headers
->response_code() != 206 && !partial_
.get() &&
1913 return BeginCacheValidation();
1916 // Partial requests should not be recorded in histograms.
1917 UpdateTransactionPattern(PATTERN_NOT_COVERED
);
1918 if (range_requested_
) {
1919 next_state_
= STATE_CACHE_QUERY_DATA
;
1922 // The request is not for a range, but we have stored just ranges.
1923 partial_
.reset(new PartialData());
1924 partial_
->SetHeaders(request_
->extra_headers
);
1925 if (!custom_request_
.get()) {
1926 custom_request_
.reset(new HttpRequestInfo(*request_
));
1927 request_
= custom_request_
.get();
1930 return ValidateEntryHeadersAndContinue();
1933 // This should only be called once per request.
1934 int HttpCache::Transaction::ValidateEntryHeadersAndContinue() {
1935 DCHECK(mode_
== READ_WRITE
);
1937 if (!partial_
->UpdateFromStoredHeaders(
1938 response_
.headers
.get(), entry_
->disk_entry
, truncated_
)) {
1939 return DoRestartPartialRequest();
1942 if (response_
.headers
->response_code() == 206)
1945 if (!partial_
->IsRequestedRangeOK()) {
1946 // The stored data is fine, but the request may be invalid.
1947 invalid_range_
= true;
1950 next_state_
= STATE_START_PARTIAL_CACHE_VALIDATION
;
1954 int HttpCache::Transaction::BeginExternallyConditionalizedRequest() {
1955 DCHECK_EQ(UPDATE
, mode_
);
1956 DCHECK(external_validation_
.initialized
);
1958 for (size_t i
= 0; i
< arraysize(kValidationHeaders
); i
++) {
1959 if (external_validation_
.values
[i
].empty())
1961 // Retrieve either the cached response's "etag" or "last-modified" header.
1962 std::string validator
;
1963 response_
.headers
->EnumerateHeader(
1965 kValidationHeaders
[i
].related_response_header_name
,
1968 if (response_
.headers
->response_code() != 200 || truncated_
||
1969 validator
.empty() || validator
!= external_validation_
.values
[i
]) {
1970 // The externally conditionalized request is not a validation request
1971 // for our existing cache entry. Proceed with caching disabled.
1972 UpdateTransactionPattern(PATTERN_NOT_COVERED
);
1973 DoneWritingToEntry(true);
1977 next_state_
= STATE_SEND_REQUEST
;
1981 int HttpCache::Transaction::RestartNetworkRequest() {
1982 DCHECK(mode_
& WRITE
|| mode_
== NONE
);
1983 DCHECK(network_trans_
.get());
1984 DCHECK_EQ(STATE_NONE
, next_state_
);
1986 next_state_
= STATE_SEND_REQUEST_COMPLETE
;
1987 int rv
= network_trans_
->RestartIgnoringLastError(io_callback_
);
1988 if (rv
!= ERR_IO_PENDING
)
1993 int HttpCache::Transaction::RestartNetworkRequestWithCertificate(
1994 X509Certificate
* client_cert
) {
1995 DCHECK(mode_
& WRITE
|| mode_
== NONE
);
1996 DCHECK(network_trans_
.get());
1997 DCHECK_EQ(STATE_NONE
, next_state_
);
1999 next_state_
= STATE_SEND_REQUEST_COMPLETE
;
2000 int rv
= network_trans_
->RestartWithCertificate(client_cert
, io_callback_
);
2001 if (rv
!= ERR_IO_PENDING
)
2006 int HttpCache::Transaction::RestartNetworkRequestWithAuth(
2007 const AuthCredentials
& credentials
) {
2008 DCHECK(mode_
& WRITE
|| mode_
== NONE
);
2009 DCHECK(network_trans_
.get());
2010 DCHECK_EQ(STATE_NONE
, next_state_
);
2012 next_state_
= STATE_SEND_REQUEST_COMPLETE
;
2013 int rv
= network_trans_
->RestartWithAuth(credentials
, io_callback_
);
2014 if (rv
!= ERR_IO_PENDING
)
2019 bool HttpCache::Transaction::RequiresValidation() {
2020 // TODO(darin): need to do more work here:
2021 // - make sure we have a matching request method
2022 // - watch out for cached responses that depend on authentication
2024 // In playback mode, nothing requires validation.
2025 if (cache_
->mode() == net::HttpCache::PLAYBACK
)
2028 if (response_
.vary_data
.is_valid() &&
2029 !response_
.vary_data
.MatchesRequest(*request_
,
2030 *response_
.headers
.get())) {
2031 vary_mismatch_
= true;
2035 if (effective_load_flags_
& LOAD_PREFERRING_CACHE
)
2038 if (effective_load_flags_
& LOAD_VALIDATE_CACHE
)
2041 if (request_
->method
== "PUT" || request_
->method
== "DELETE")
2044 if (response_
.headers
->RequiresValidation(
2045 response_
.request_time
, response_
.response_time
, Time::Now())) {
2052 bool HttpCache::Transaction::ConditionalizeRequest() {
2053 DCHECK(response_
.headers
.get());
2055 if (request_
->method
== "PUT" || request_
->method
== "DELETE")
2058 // This only makes sense for cached 200 or 206 responses.
2059 if (response_
.headers
->response_code() != 200 &&
2060 response_
.headers
->response_code() != 206) {
2064 // We should have handled this case before.
2065 DCHECK(response_
.headers
->response_code() != 206 ||
2066 response_
.headers
->HasStrongValidators());
2068 // Just use the first available ETag and/or Last-Modified header value.
2069 // TODO(darin): Or should we use the last?
2071 std::string etag_value
;
2072 if (response_
.headers
->GetHttpVersion() >= HttpVersion(1, 1))
2073 response_
.headers
->EnumerateHeader(NULL
, "etag", &etag_value
);
2075 std::string last_modified_value
;
2076 if (!vary_mismatch_
) {
2077 response_
.headers
->EnumerateHeader(NULL
, "last-modified",
2078 &last_modified_value
);
2081 if (etag_value
.empty() && last_modified_value
.empty())
2084 if (!partial_
.get()) {
2085 // Need to customize the request, so this forces us to allocate :(
2086 custom_request_
.reset(new HttpRequestInfo(*request_
));
2087 request_
= custom_request_
.get();
2089 DCHECK(custom_request_
.get());
2091 bool use_if_range
= partial_
.get() && !partial_
->IsCurrentRangeCached() &&
2094 if (!etag_value
.empty()) {
2096 // We don't want to switch to WRITE mode if we don't have this block of a
2097 // byte-range request because we may have other parts cached.
2098 custom_request_
->extra_headers
.SetHeader(
2099 HttpRequestHeaders::kIfRange
, etag_value
);
2101 custom_request_
->extra_headers
.SetHeader(
2102 HttpRequestHeaders::kIfNoneMatch
, etag_value
);
2104 // For byte-range requests, make sure that we use only one way to validate
2106 if (partial_
.get() && !partial_
->IsCurrentRangeCached())
2110 if (!last_modified_value
.empty()) {
2112 custom_request_
->extra_headers
.SetHeader(
2113 HttpRequestHeaders::kIfRange
, last_modified_value
);
2115 custom_request_
->extra_headers
.SetHeader(
2116 HttpRequestHeaders::kIfModifiedSince
, last_modified_value
);
2123 // We just received some headers from the server. We may have asked for a range,
2124 // in which case partial_ has an object. This could be the first network request
2125 // we make to fulfill the original request, or we may be already reading (from
2126 // the net and / or the cache). If we are not expecting a certain response, we
2127 // just bypass the cache for this request (but again, maybe we are reading), and
2128 // delete partial_ (so we are not able to "fix" the headers that we return to
2129 // the user). This results in either a weird response for the caller (we don't
2130 // expect it after all), or maybe a range that was not exactly what it was asked
2133 // If the server is simply telling us that the resource has changed, we delete
2134 // the cached entry and restart the request as the caller intended (by returning
2135 // false from this method). However, we may not be able to do that at any point,
2136 // for instance if we already returned the headers to the user.
2138 // WARNING: Whenever this code returns false, it has to make sure that the next
2139 // time it is called it will return true so that we don't keep retrying the
2141 bool HttpCache::Transaction::ValidatePartialResponse() {
2142 const HttpResponseHeaders
* headers
= new_response_
->headers
.get();
2143 int response_code
= headers
->response_code();
2144 bool partial_response
= (response_code
== 206);
2145 handling_206_
= false;
2147 if (!entry_
|| request_
->method
!= "GET")
2150 if (invalid_range_
) {
2151 // We gave up trying to match this request with the stored data. If the
2152 // server is ok with the request, delete the entry, otherwise just ignore
2155 if (partial_response
|| response_code
== 200) {
2156 DoomPartialEntry(true);
2159 if (response_code
== 304)
2161 IgnoreRangeRequest();
2166 if (!partial_
.get()) {
2167 // We are not expecting 206 but we may have one.
2168 if (partial_response
)
2169 IgnoreRangeRequest();
2174 // TODO(rvargas): Do we need to consider other results here?.
2175 bool failure
= response_code
== 200 || response_code
== 416;
2177 if (partial_
->IsCurrentRangeCached()) {
2178 // We asked for "If-None-Match: " so a 206 means a new object.
2179 if (partial_response
)
2182 if (response_code
== 304 && partial_
->ResponseHeadersOK(headers
))
2185 // We asked for "If-Range: " so a 206 means just another range.
2186 if (partial_response
&& partial_
->ResponseHeadersOK(headers
)) {
2187 handling_206_
= true;
2191 if (!reading_
&& !is_sparse_
&& !partial_response
) {
2192 // See if we can ignore the fact that we issued a byte range request.
2193 // If the server sends 200, just store it. If it sends an error, redirect
2194 // or something else, we may store the response as long as we didn't have
2195 // anything already stored.
2196 if (response_code
== 200 ||
2197 (!truncated_
&& response_code
!= 304 && response_code
!= 416)) {
2198 // The server is sending something else, and we can save it.
2199 DCHECK((truncated_
&& !partial_
->IsLastRange()) || range_requested_
);
2206 // 304 is not expected here, but we'll spare the entry (unless it was
2213 // We cannot truncate this entry, it has to be deleted.
2214 UpdateTransactionPattern(PATTERN_NOT_COVERED
);
2215 DoomPartialEntry(false);
2217 if (!reading_
&& !partial_
->IsLastRange()) {
2218 // We'll attempt to issue another network request, this time without us
2219 // messing up the headers.
2220 partial_
->RestoreHeaders(&custom_request_
->extra_headers
);
2225 LOG(WARNING
) << "Failed to revalidate partial entry";
2230 IgnoreRangeRequest();
2234 void HttpCache::Transaction::IgnoreRangeRequest() {
2235 // We have a problem. We may or may not be reading already (in which case we
2236 // returned the headers), but we'll just pretend that this request is not
2237 // using the cache and see what happens. Most likely this is the first
2238 // response from the server (it's not changing its mind midway, right?).
2239 UpdateTransactionPattern(PATTERN_NOT_COVERED
);
2241 DoneWritingToEntry(mode_
!= WRITE
);
2242 else if (mode_
& READ
&& entry_
)
2243 cache_
->DoneReadingFromEntry(entry_
, this);
2245 partial_
.reset(NULL
);
2250 void HttpCache::Transaction::FailRangeRequest() {
2251 response_
= *new_response_
;
2252 partial_
->FixResponseHeaders(response_
.headers
.get(), false);
2255 int HttpCache::Transaction::SetupEntryForRead() {
2257 ResetNetworkTransaction();
2258 if (partial_
.get()) {
2259 if (truncated_
|| is_sparse_
|| !invalid_range_
) {
2260 // We are going to return the saved response headers to the caller, so
2261 // we may need to adjust them first.
2262 next_state_
= STATE_PARTIAL_HEADERS_RECEIVED
;
2268 cache_
->ConvertWriterToReader(entry_
);
2271 if (entry_
->disk_entry
->GetDataSize(kMetadataIndex
))
2272 next_state_
= STATE_CACHE_READ_METADATA
;
2277 int HttpCache::Transaction::ReadFromNetwork(IOBuffer
* data
, int data_len
) {
2279 io_buf_len_
= data_len
;
2280 next_state_
= STATE_NETWORK_READ
;
2284 int HttpCache::Transaction::ReadFromEntry(IOBuffer
* data
, int data_len
) {
2286 io_buf_len_
= data_len
;
2287 next_state_
= STATE_CACHE_READ_DATA
;
2291 int HttpCache::Transaction::WriteToEntry(int index
, int offset
,
2292 IOBuffer
* data
, int data_len
,
2293 const CompletionCallback
& callback
) {
2298 if (!partial_
.get() || !data_len
) {
2299 rv
= entry_
->disk_entry
->WriteData(index
, offset
, data
, data_len
, callback
,
2302 rv
= partial_
->CacheWrite(entry_
->disk_entry
, data
, data_len
, callback
);
2307 int HttpCache::Transaction::WriteResponseInfoToEntry(bool truncated
) {
2308 next_state_
= STATE_CACHE_WRITE_RESPONSE_COMPLETE
;
2312 // Do not cache no-store content (unless we are record mode). Do not cache
2313 // content with cert errors either. This is to prevent not reporting net
2314 // errors when loading a resource from the cache. When we load a page over
2315 // HTTPS with a cert error we show an SSL blocking page. If the user clicks
2316 // proceed we reload the resource ignoring the errors. The loaded resource
2317 // is then cached. If that resource is subsequently loaded from the cache,
2318 // no net error is reported (even though the cert status contains the actual
2319 // errors) and no SSL blocking page is shown. An alternative would be to
2320 // reverse-map the cert status to a net error and replay the net error.
2321 if ((cache_
->mode() != RECORD
&&
2322 response_
.headers
->HasHeaderValue("cache-control", "no-store")) ||
2323 net::IsCertStatusError(response_
.ssl_info
.cert_status
)) {
2324 DoneWritingToEntry(false);
2325 if (net_log_
.IsLogging())
2326 net_log_
.EndEvent(NetLog::TYPE_HTTP_CACHE_WRITE_INFO
);
2330 // When writing headers, we normally only write the non-transient
2331 // headers; when in record mode, record everything.
2332 bool skip_transient_headers
= (cache_
->mode() != RECORD
);
2335 DCHECK_EQ(200, response_
.headers
->response_code());
2337 scoped_refptr
<PickledIOBuffer
> data(new PickledIOBuffer());
2338 response_
.Persist(data
->pickle(), skip_transient_headers
, truncated
);
2341 io_buf_len_
= data
->pickle()->size();
2342 return entry_
->disk_entry
->WriteData(kResponseInfoIndex
, 0, data
.get(),
2343 io_buf_len_
, io_callback_
, true);
2346 int HttpCache::Transaction::AppendResponseDataToEntry(
2347 IOBuffer
* data
, int data_len
, const CompletionCallback
& callback
) {
2348 if (!entry_
|| !data_len
)
2351 int current_size
= entry_
->disk_entry
->GetDataSize(kResponseContentIndex
);
2352 return WriteToEntry(kResponseContentIndex
, current_size
, data
, data_len
,
2356 void HttpCache::Transaction::DoneWritingToEntry(bool success
) {
2362 cache_
->DoneWritingToEntry(entry_
, success
);
2364 mode_
= NONE
; // switch to 'pass through' mode
2367 int HttpCache::Transaction::OnCacheReadError(int result
, bool restart
) {
2368 DLOG(ERROR
) << "ReadData failed: " << result
;
2369 const int result_for_histogram
= std::max(0, -result
);
2371 UMA_HISTOGRAM_SPARSE_SLOWLY("HttpCache.ReadErrorRestartable",
2372 result_for_histogram
);
2374 UMA_HISTOGRAM_SPARSE_SLOWLY("HttpCache.ReadErrorNonRestartable",
2375 result_for_histogram
);
2378 // Avoid using this entry in the future.
2380 cache_
->DoomActiveEntry(cache_key_
);
2384 DCHECK(!network_trans_
.get());
2385 cache_
->DoneWithEntry(entry_
, this, false);
2389 next_state_
= STATE_GET_BACKEND
;
2393 return ERR_CACHE_READ_FAILURE
;
2396 void HttpCache::Transaction::OnAddToEntryTimeout(base::TimeTicks start_time
) {
2397 if (entry_lock_waiting_since_
!= start_time
)
2400 DCHECK_EQ(next_state_
, STATE_ADD_TO_ENTRY_COMPLETE
);
2405 cache_
->RemovePendingTransaction(this);
2406 OnIOComplete(ERR_CACHE_LOCK_TIMEOUT
);
2409 void HttpCache::Transaction::DoomPartialEntry(bool delete_object
) {
2410 DVLOG(2) << "DoomPartialEntry";
2411 int rv
= cache_
->DoomEntry(cache_key_
, NULL
);
2413 cache_
->DoneWithEntry(entry_
, this, false);
2417 partial_
.reset(NULL
);
2420 int HttpCache::Transaction::DoPartialNetworkReadCompleted(int result
) {
2421 partial_
->OnNetworkReadCompleted(result
);
2424 // We need to move on to the next range.
2425 ResetNetworkTransaction();
2426 next_state_
= STATE_START_PARTIAL_CACHE_VALIDATION
;
2431 int HttpCache::Transaction::DoPartialCacheReadCompleted(int result
) {
2432 partial_
->OnCacheReadCompleted(result
);
2434 if (result
== 0 && mode_
== READ_WRITE
) {
2435 // We need to move on to the next range.
2436 next_state_
= STATE_START_PARTIAL_CACHE_VALIDATION
;
2437 } else if (result
< 0) {
2438 return OnCacheReadError(result
, false);
2443 int HttpCache::Transaction::DoRestartPartialRequest() {
2444 // The stored data cannot be used. Get rid of it and restart this request.
2445 // We need to also reset the |truncated_| flag as a new entry is created.
2446 DoomPartialEntry(!range_requested_
);
2449 next_state_
= STATE_INIT_ENTRY
;
2453 void HttpCache::Transaction::ResetNetworkTransaction() {
2454 DCHECK(!old_network_trans_load_timing_
);
2455 DCHECK(network_trans_
);
2456 LoadTimingInfo load_timing
;
2457 if (network_trans_
->GetLoadTimingInfo(&load_timing
))
2458 old_network_trans_load_timing_
.reset(new LoadTimingInfo(load_timing
));
2459 total_received_bytes_
+= network_trans_
->GetTotalReceivedBytes();
2460 network_trans_
.reset();
2463 // Histogram data from the end of 2010 show the following distribution of
2464 // response headers:
2466 // Content-Length............... 87%
2467 // Date......................... 98%
2468 // Last-Modified................ 49%
2469 // Etag......................... 19%
2470 // Accept-Ranges: bytes......... 25%
2471 // Accept-Ranges: none.......... 0.4%
2472 // Strong Validator............. 50%
2473 // Strong Validator + ranges.... 24%
2474 // Strong Validator + CL........ 49%
2476 bool HttpCache::Transaction::CanResume(bool has_data
) {
2477 // Double check that there is something worth keeping.
2478 if (has_data
&& !entry_
->disk_entry
->GetDataSize(kResponseContentIndex
))
2481 if (request_
->method
!= "GET")
2484 // Note that if this is a 206, content-length was already fixed after calling
2485 // PartialData::ResponseHeadersOK().
2486 if (response_
.headers
->GetContentLength() <= 0 ||
2487 response_
.headers
->HasHeaderValue("Accept-Ranges", "none") ||
2488 !response_
.headers
->HasStrongValidators()) {
2495 void HttpCache::Transaction::UpdateTransactionPattern(
2496 TransactionPattern new_transaction_pattern
) {
2497 if (transaction_pattern_
== PATTERN_NOT_COVERED
)
2499 DCHECK(transaction_pattern_
== PATTERN_UNDEFINED
||
2500 new_transaction_pattern
== PATTERN_NOT_COVERED
);
2501 transaction_pattern_
= new_transaction_pattern
;
2504 void HttpCache::Transaction::RecordHistograms() {
2505 DCHECK_NE(PATTERN_UNDEFINED
, transaction_pattern_
);
2506 if (!cache_
.get() || !cache_
->GetCurrentBackend() ||
2507 cache_
->GetCurrentBackend()->GetCacheType() != DISK_CACHE
||
2508 cache_
->mode() != NORMAL
|| request_
->method
!= "GET") {
2511 UMA_HISTOGRAM_ENUMERATION(
2512 "HttpCache.Pattern", transaction_pattern_
, PATTERN_MAX
);
2513 if (transaction_pattern_
== PATTERN_NOT_COVERED
)
2515 DCHECK(!range_requested_
);
2516 DCHECK(!first_cache_access_since_
.is_null());
2518 TimeDelta total_time
= base::TimeTicks::Now() - first_cache_access_since_
;
2520 UMA_HISTOGRAM_TIMES("HttpCache.AccessToDone", total_time
);
2522 bool did_send_request
= !send_request_since_
.is_null();
2524 (did_send_request
&&
2525 (transaction_pattern_
== PATTERN_ENTRY_NOT_CACHED
||
2526 transaction_pattern_
== PATTERN_ENTRY_VALIDATED
||
2527 transaction_pattern_
== PATTERN_ENTRY_UPDATED
||
2528 transaction_pattern_
== PATTERN_ENTRY_CANT_CONDITIONALIZE
)) ||
2529 (!did_send_request
&& transaction_pattern_
== PATTERN_ENTRY_USED
));
2531 if (!did_send_request
) {
2532 DCHECK(transaction_pattern_
== PATTERN_ENTRY_USED
);
2533 UMA_HISTOGRAM_TIMES("HttpCache.AccessToDone.Used", total_time
);
2537 TimeDelta before_send_time
= send_request_since_
- first_cache_access_since_
;
2538 int before_send_percent
=
2539 total_time
.ToInternalValue() == 0 ? 0
2540 : before_send_time
* 100 / total_time
;
2541 DCHECK_LE(0, before_send_percent
);
2542 DCHECK_GE(100, before_send_percent
);
2544 UMA_HISTOGRAM_TIMES("HttpCache.AccessToDone.SentRequest", total_time
);
2545 UMA_HISTOGRAM_TIMES("HttpCache.BeforeSend", before_send_time
);
2546 UMA_HISTOGRAM_PERCENTAGE("HttpCache.PercentBeforeSend", before_send_percent
);
2548 // TODO(gavinp): Remove or minimize these histograms, particularly the ones
2549 // below this comment after we have received initial data.
2550 switch (transaction_pattern_
) {
2551 case PATTERN_ENTRY_CANT_CONDITIONALIZE
: {
2552 UMA_HISTOGRAM_TIMES("HttpCache.BeforeSend.CantConditionalize",
2554 UMA_HISTOGRAM_PERCENTAGE("HttpCache.PercentBeforeSend.CantConditionalize",
2555 before_send_percent
);
2558 case PATTERN_ENTRY_NOT_CACHED
: {
2559 UMA_HISTOGRAM_TIMES("HttpCache.BeforeSend.NotCached", before_send_time
);
2560 UMA_HISTOGRAM_PERCENTAGE("HttpCache.PercentBeforeSend.NotCached",
2561 before_send_percent
);
2564 case PATTERN_ENTRY_VALIDATED
: {
2565 UMA_HISTOGRAM_TIMES("HttpCache.BeforeSend.Validated", before_send_time
);
2566 UMA_HISTOGRAM_PERCENTAGE("HttpCache.PercentBeforeSend.Validated",
2567 before_send_percent
);
2570 case PATTERN_ENTRY_UPDATED
: {
2571 UMA_HISTOGRAM_TIMES("HttpCache.BeforeSend.Updated", before_send_time
);
2572 UMA_HISTOGRAM_PERCENTAGE("HttpCache.PercentBeforeSend.Updated",
2573 before_send_percent
);
2581 void HttpCache::Transaction::OnIOComplete(int result
) {