Lots of random cleanups, mostly for native_theme_win.cc:
[chromium-blink-merge.git] / net / http / http_cache_transaction.cc
blobaba792330bf4dcf92e78deeb88ff44ff88fc663f
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"
9 #if defined(OS_POSIX)
10 #include <unistd.h>
11 #endif
13 #include <algorithm>
14 #include <string>
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/disk_based_cert_cache.h"
36 #include "net/http/http_network_session.h"
37 #include "net/http/http_request_info.h"
38 #include "net/http/http_response_headers.h"
39 #include "net/http/http_transaction.h"
40 #include "net/http/http_util.h"
41 #include "net/http/partial_data.h"
42 #include "net/ssl/ssl_cert_request_info.h"
43 #include "net/ssl/ssl_config_service.h"
45 using base::Time;
46 using base::TimeDelta;
47 using base::TimeTicks;
49 namespace {
51 // Stores data relevant to the statistics of writing and reading entire
52 // certificate chains using DiskBasedCertCache. |num_pending_ops| is the number
53 // of certificates in the chain that have pending operations in the
54 // DiskBasedCertCache. |start_time| is the time that the read and write
55 // commands began being issued to the DiskBasedCertCache.
56 // TODO(brandonsalmon): Remove this when it is no longer necessary to
57 // collect data.
58 class SharedChainData : public base::RefCounted<SharedChainData> {
59 public:
60 SharedChainData(int num_ops, TimeTicks start)
61 : num_pending_ops(num_ops), start_time(start) {}
63 int num_pending_ops;
64 TimeTicks start_time;
66 private:
67 friend class base::RefCounted<SharedChainData>;
68 ~SharedChainData() {}
69 DISALLOW_COPY_AND_ASSIGN(SharedChainData);
72 // Used to obtain a cache entry key for an OSCertHandle.
73 // TODO(brandonsalmon): Remove this when cache keys are stored
74 // and no longer have to be recomputed to retrieve the OSCertHandle
75 // from the disk.
76 std::string GetCacheKeyForCert(net::X509Certificate::OSCertHandle cert_handle) {
77 net::SHA1HashValue fingerprint =
78 net::X509Certificate::CalculateFingerprint(cert_handle);
80 return "cert:" +
81 base::HexEncode(fingerprint.data, arraysize(fingerprint.data));
84 // |dist_from_root| indicates the position of the read certificate in the
85 // certificate chain, 0 indicating it is the root. |is_leaf| indicates
86 // whether or not the read certificate was the leaf of the chain.
87 // |shared_chain_data| contains data shared by each certificate in
88 // the chain.
89 void OnCertReadIOComplete(
90 int dist_from_root,
91 bool is_leaf,
92 const scoped_refptr<SharedChainData>& shared_chain_data,
93 net::X509Certificate::OSCertHandle cert_handle) {
94 // If |num_pending_ops| is one, this was the last pending read operation
95 // for this chain of certificates. The total time used to read the chain
96 // can be calculated by subtracting the starting time from Now().
97 shared_chain_data->num_pending_ops--;
98 if (!shared_chain_data->num_pending_ops) {
99 const TimeDelta read_chain_wait =
100 TimeTicks::Now() - shared_chain_data->start_time;
101 UMA_HISTOGRAM_CUSTOM_TIMES("DiskBasedCertCache.ChainReadTime",
102 read_chain_wait,
103 base::TimeDelta::FromMilliseconds(1),
104 base::TimeDelta::FromMinutes(10),
105 50);
108 bool success = (cert_handle != NULL);
109 if (is_leaf)
110 UMA_HISTOGRAM_BOOLEAN("DiskBasedCertCache.CertIoReadSuccessLeaf", success);
112 if (success)
113 UMA_HISTOGRAM_CUSTOM_COUNTS(
114 "DiskBasedCertCache.CertIoReadSuccess", dist_from_root, 0, 10, 7);
115 else
116 UMA_HISTOGRAM_CUSTOM_COUNTS(
117 "DiskBasedCertCache.CertIoReadFailure", dist_from_root, 0, 10, 7);
120 // |dist_from_root| indicates the position of the written certificate in the
121 // certificate chain, 0 indicating it is the root. |is_leaf| indicates
122 // whether or not the written certificate was the leaf of the chain.
123 // |shared_chain_data| contains data shared by each certificate in
124 // the chain.
125 void OnCertWriteIOComplete(
126 int dist_from_root,
127 bool is_leaf,
128 const scoped_refptr<SharedChainData>& shared_chain_data,
129 const std::string& key) {
130 // If |num_pending_ops| is one, this was the last pending write operation
131 // for this chain of certificates. The total time used to write the chain
132 // can be calculated by subtracting the starting time from Now().
133 shared_chain_data->num_pending_ops--;
134 if (!shared_chain_data->num_pending_ops) {
135 const TimeDelta write_chain_wait =
136 TimeTicks::Now() - shared_chain_data->start_time;
137 UMA_HISTOGRAM_CUSTOM_TIMES("DiskBasedCertCache.ChainWriteTime",
138 write_chain_wait,
139 base::TimeDelta::FromMilliseconds(1),
140 base::TimeDelta::FromMinutes(10),
141 50);
144 bool success = !key.empty();
145 if (is_leaf)
146 UMA_HISTOGRAM_BOOLEAN("DiskBasedCertCache.CertIoWriteSuccessLeaf", success);
148 if (success)
149 UMA_HISTOGRAM_CUSTOM_COUNTS(
150 "DiskBasedCertCache.CertIoWriteSuccess", dist_from_root, 0, 10, 7);
151 else
152 UMA_HISTOGRAM_CUSTOM_COUNTS(
153 "DiskBasedCertCache.CertIoWriteFailure", dist_from_root, 0, 10, 7);
156 // From http://tools.ietf.org/html/draft-ietf-httpbis-p6-cache-21#section-6
157 // a "non-error response" is one with a 2xx (Successful) or 3xx
158 // (Redirection) status code.
159 bool NonErrorResponse(int status_code) {
160 int status_code_range = status_code / 100;
161 return status_code_range == 2 || status_code_range == 3;
164 // Error codes that will be considered indicative of a page being offline/
165 // unreachable for LOAD_FROM_CACHE_IF_OFFLINE.
166 bool IsOfflineError(int error) {
167 return (error == net::ERR_NAME_NOT_RESOLVED ||
168 error == net::ERR_INTERNET_DISCONNECTED ||
169 error == net::ERR_ADDRESS_UNREACHABLE ||
170 error == net::ERR_CONNECTION_TIMED_OUT);
173 // Enum for UMA, indicating the status (with regard to offline mode) of
174 // a particular request.
175 enum RequestOfflineStatus {
176 // A cache transaction hit in cache (data was present and not stale)
177 // and returned it.
178 OFFLINE_STATUS_FRESH_CACHE,
180 // A network request was required for a cache entry, and it succeeded.
181 OFFLINE_STATUS_NETWORK_SUCCEEDED,
183 // A network request was required for a cache entry, and it failed with
184 // a non-offline error.
185 OFFLINE_STATUS_NETWORK_FAILED,
187 // A network request was required for a cache entry, it failed with an
188 // offline error, and we could serve stale data if
189 // LOAD_FROM_CACHE_IF_OFFLINE was set.
190 OFFLINE_STATUS_DATA_AVAILABLE_OFFLINE,
192 // A network request was required for a cache entry, it failed with
193 // an offline error, and there was no servable data in cache (even
194 // stale data).
195 OFFLINE_STATUS_DATA_UNAVAILABLE_OFFLINE,
197 OFFLINE_STATUS_MAX_ENTRIES
200 void RecordOfflineStatus(int load_flags, RequestOfflineStatus status) {
201 // Restrict to main frame to keep statistics close to
202 // "would have shown them something useful if offline mode was enabled".
203 if (load_flags & net::LOAD_MAIN_FRAME) {
204 UMA_HISTOGRAM_ENUMERATION("HttpCache.OfflineStatus", status,
205 OFFLINE_STATUS_MAX_ENTRIES);
209 // TODO(rvargas): Remove once we get the data.
210 void RecordVaryHeaderHistogram(const net::HttpResponseInfo* response) {
211 enum VaryType {
212 VARY_NOT_PRESENT,
213 VARY_UA,
214 VARY_OTHER,
215 VARY_MAX
217 VaryType vary = VARY_NOT_PRESENT;
218 if (response->vary_data.is_valid()) {
219 vary = VARY_OTHER;
220 if (response->headers->HasHeaderValue("vary", "user-agent"))
221 vary = VARY_UA;
223 UMA_HISTOGRAM_ENUMERATION("HttpCache.Vary", vary, VARY_MAX);
226 void RecordNoStoreHeaderHistogram(int load_flags,
227 const net::HttpResponseInfo* response) {
228 if (load_flags & net::LOAD_MAIN_FRAME) {
229 UMA_HISTOGRAM_BOOLEAN(
230 "Net.MainFrameNoStore",
231 response->headers->HasHeaderValue("cache-control", "no-store"));
235 } // namespace
237 namespace net {
239 struct HeaderNameAndValue {
240 const char* name;
241 const char* value;
244 // If the request includes one of these request headers, then avoid caching
245 // to avoid getting confused.
246 static const HeaderNameAndValue kPassThroughHeaders[] = {
247 { "if-unmodified-since", NULL }, // causes unexpected 412s
248 { "if-match", NULL }, // causes unexpected 412s
249 { "if-range", NULL },
250 { NULL, NULL }
253 struct ValidationHeaderInfo {
254 const char* request_header_name;
255 const char* related_response_header_name;
258 static const ValidationHeaderInfo kValidationHeaders[] = {
259 { "if-modified-since", "last-modified" },
260 { "if-none-match", "etag" },
263 // If the request includes one of these request headers, then avoid reusing
264 // our cached copy if any.
265 static const HeaderNameAndValue kForceFetchHeaders[] = {
266 { "cache-control", "no-cache" },
267 { "pragma", "no-cache" },
268 { NULL, NULL }
271 // If the request includes one of these request headers, then force our
272 // cached copy (if any) to be revalidated before reusing it.
273 static const HeaderNameAndValue kForceValidateHeaders[] = {
274 { "cache-control", "max-age=0" },
275 { NULL, NULL }
278 static bool HeaderMatches(const HttpRequestHeaders& headers,
279 const HeaderNameAndValue* search) {
280 for (; search->name; ++search) {
281 std::string header_value;
282 if (!headers.GetHeader(search->name, &header_value))
283 continue;
285 if (!search->value)
286 return true;
288 HttpUtil::ValuesIterator v(header_value.begin(), header_value.end(), ',');
289 while (v.GetNext()) {
290 if (LowerCaseEqualsASCII(v.value_begin(), v.value_end(), search->value))
291 return true;
294 return false;
297 //-----------------------------------------------------------------------------
299 HttpCache::Transaction::Transaction(
300 RequestPriority priority,
301 HttpCache* cache)
302 : next_state_(STATE_NONE),
303 request_(NULL),
304 priority_(priority),
305 cache_(cache->GetWeakPtr()),
306 entry_(NULL),
307 new_entry_(NULL),
308 new_response_(NULL),
309 mode_(NONE),
310 target_state_(STATE_NONE),
311 reading_(false),
312 invalid_range_(false),
313 truncated_(false),
314 is_sparse_(false),
315 range_requested_(false),
316 handling_206_(false),
317 cache_pending_(false),
318 done_reading_(false),
319 vary_mismatch_(false),
320 couldnt_conditionalize_request_(false),
321 bypass_lock_for_test_(false),
322 io_buf_len_(0),
323 read_offset_(0),
324 effective_load_flags_(0),
325 write_len_(0),
326 weak_factory_(this),
327 io_callback_(base::Bind(&Transaction::OnIOComplete,
328 weak_factory_.GetWeakPtr())),
329 transaction_pattern_(PATTERN_UNDEFINED),
330 total_received_bytes_(0),
331 websocket_handshake_stream_base_create_helper_(NULL) {
332 COMPILE_ASSERT(HttpCache::Transaction::kNumValidationHeaders ==
333 arraysize(kValidationHeaders),
334 Invalid_number_of_validation_headers);
337 HttpCache::Transaction::~Transaction() {
338 // We may have to issue another IO, but we should never invoke the callback_
339 // after this point.
340 callback_.Reset();
342 if (cache_) {
343 if (entry_) {
344 bool cancel_request = reading_ && response_.headers;
345 if (cancel_request) {
346 if (partial_) {
347 entry_->disk_entry->CancelSparseIO();
348 } else {
349 cancel_request &= (response_.headers->response_code() == 200);
353 cache_->DoneWithEntry(entry_, this, cancel_request);
354 } else if (cache_pending_) {
355 cache_->RemovePendingTransaction(this);
360 int HttpCache::Transaction::WriteMetadata(IOBuffer* buf, int buf_len,
361 const CompletionCallback& callback) {
362 DCHECK(buf);
363 DCHECK_GT(buf_len, 0);
364 DCHECK(!callback.is_null());
365 if (!cache_.get() || !entry_)
366 return ERR_UNEXPECTED;
368 // We don't need to track this operation for anything.
369 // It could be possible to check if there is something already written and
370 // avoid writing again (it should be the same, right?), but let's allow the
371 // caller to "update" the contents with something new.
372 return entry_->disk_entry->WriteData(kMetadataIndex, 0, buf, buf_len,
373 callback, true);
376 bool HttpCache::Transaction::AddTruncatedFlag() {
377 DCHECK(mode_ & WRITE || mode_ == NONE);
379 // Don't set the flag for sparse entries.
380 if (partial_.get() && !truncated_)
381 return true;
383 if (!CanResume(true))
384 return false;
386 // We may have received the whole resource already.
387 if (done_reading_)
388 return true;
390 truncated_ = true;
391 target_state_ = STATE_NONE;
392 next_state_ = STATE_CACHE_WRITE_TRUNCATED_RESPONSE;
393 DoLoop(OK);
394 return true;
397 LoadState HttpCache::Transaction::GetWriterLoadState() const {
398 if (network_trans_.get())
399 return network_trans_->GetLoadState();
400 if (entry_ || !request_)
401 return LOAD_STATE_IDLE;
402 return LOAD_STATE_WAITING_FOR_CACHE;
405 const BoundNetLog& HttpCache::Transaction::net_log() const {
406 return net_log_;
409 int HttpCache::Transaction::Start(const HttpRequestInfo* request,
410 const CompletionCallback& callback,
411 const BoundNetLog& net_log) {
412 DCHECK(request);
413 DCHECK(!callback.is_null());
415 // Ensure that we only have one asynchronous call at a time.
416 DCHECK(callback_.is_null());
417 DCHECK(!reading_);
418 DCHECK(!network_trans_.get());
419 DCHECK(!entry_);
421 if (!cache_.get())
422 return ERR_UNEXPECTED;
424 SetRequest(net_log, request);
426 // We have to wait until the backend is initialized so we start the SM.
427 next_state_ = STATE_GET_BACKEND;
428 int rv = DoLoop(OK);
430 // Setting this here allows us to check for the existence of a callback_ to
431 // determine if we are still inside Start.
432 if (rv == ERR_IO_PENDING)
433 callback_ = callback;
435 return rv;
438 int HttpCache::Transaction::RestartIgnoringLastError(
439 const CompletionCallback& callback) {
440 DCHECK(!callback.is_null());
442 // Ensure that we only have one asynchronous call at a time.
443 DCHECK(callback_.is_null());
445 if (!cache_.get())
446 return ERR_UNEXPECTED;
448 int rv = RestartNetworkRequest();
450 if (rv == ERR_IO_PENDING)
451 callback_ = callback;
453 return rv;
456 int HttpCache::Transaction::RestartWithCertificate(
457 X509Certificate* client_cert,
458 const CompletionCallback& callback) {
459 DCHECK(!callback.is_null());
461 // Ensure that we only have one asynchronous call at a time.
462 DCHECK(callback_.is_null());
464 if (!cache_.get())
465 return ERR_UNEXPECTED;
467 int rv = RestartNetworkRequestWithCertificate(client_cert);
469 if (rv == ERR_IO_PENDING)
470 callback_ = callback;
472 return rv;
475 int HttpCache::Transaction::RestartWithAuth(
476 const AuthCredentials& credentials,
477 const CompletionCallback& callback) {
478 DCHECK(auth_response_.headers.get());
479 DCHECK(!callback.is_null());
481 // Ensure that we only have one asynchronous call at a time.
482 DCHECK(callback_.is_null());
484 if (!cache_.get())
485 return ERR_UNEXPECTED;
487 // Clear the intermediate response since we are going to start over.
488 auth_response_ = HttpResponseInfo();
490 int rv = RestartNetworkRequestWithAuth(credentials);
492 if (rv == ERR_IO_PENDING)
493 callback_ = callback;
495 return rv;
498 bool HttpCache::Transaction::IsReadyToRestartForAuth() {
499 if (!network_trans_.get())
500 return false;
501 return network_trans_->IsReadyToRestartForAuth();
504 int HttpCache::Transaction::Read(IOBuffer* buf, int buf_len,
505 const CompletionCallback& callback) {
506 DCHECK(buf);
507 DCHECK_GT(buf_len, 0);
508 DCHECK(!callback.is_null());
510 DCHECK(callback_.is_null());
512 if (!cache_.get())
513 return ERR_UNEXPECTED;
515 // If we have an intermediate auth response at this point, then it means the
516 // user wishes to read the network response (the error page). If there is a
517 // previous response in the cache then we should leave it intact.
518 if (auth_response_.headers.get() && mode_ != NONE) {
519 UpdateTransactionPattern(PATTERN_NOT_COVERED);
520 DCHECK(mode_ & WRITE);
521 DoneWritingToEntry(mode_ == READ_WRITE);
522 mode_ = NONE;
525 reading_ = true;
526 int rv;
528 switch (mode_) {
529 case READ_WRITE:
530 DCHECK(partial_.get());
531 if (!network_trans_.get()) {
532 // We are just reading from the cache, but we may be writing later.
533 rv = ReadFromEntry(buf, buf_len);
534 break;
536 case NONE:
537 case WRITE:
538 DCHECK(network_trans_.get());
539 rv = ReadFromNetwork(buf, buf_len);
540 break;
541 case READ:
542 rv = ReadFromEntry(buf, buf_len);
543 break;
544 default:
545 NOTREACHED();
546 rv = ERR_FAILED;
549 if (rv == ERR_IO_PENDING) {
550 DCHECK(callback_.is_null());
551 callback_ = callback;
553 return rv;
556 void HttpCache::Transaction::StopCaching() {
557 // We really don't know where we are now. Hopefully there is no operation in
558 // progress, but nothing really prevents this method to be called after we
559 // returned ERR_IO_PENDING. We cannot attempt to truncate the entry at this
560 // point because we need the state machine for that (and even if we are really
561 // free, that would be an asynchronous operation). In other words, keep the
562 // entry how it is (it will be marked as truncated at destruction), and let
563 // the next piece of code that executes know that we are now reading directly
564 // from the net.
565 // TODO(mmenke): This doesn't release the lock on the cache entry, so a
566 // future request for the resource will be blocked on this one.
567 // Fix this.
568 if (cache_.get() && entry_ && (mode_ & WRITE) && network_trans_.get() &&
569 !is_sparse_ && !range_requested_) {
570 mode_ = NONE;
574 bool HttpCache::Transaction::GetFullRequestHeaders(
575 HttpRequestHeaders* headers) const {
576 if (network_trans_)
577 return network_trans_->GetFullRequestHeaders(headers);
579 // TODO(ttuttle): Read headers from cache.
580 return false;
583 int64 HttpCache::Transaction::GetTotalReceivedBytes() const {
584 int64 total_received_bytes = total_received_bytes_;
585 if (network_trans_)
586 total_received_bytes += network_trans_->GetTotalReceivedBytes();
587 return total_received_bytes;
590 void HttpCache::Transaction::DoneReading() {
591 if (cache_.get() && entry_) {
592 DCHECK_NE(mode_, UPDATE);
593 if (mode_ & WRITE) {
594 DoneWritingToEntry(true);
595 } else if (mode_ & READ) {
596 // It is necessary to check mode_ & READ because it is possible
597 // for mode_ to be NONE and entry_ non-NULL with a write entry
598 // if StopCaching was called.
599 cache_->DoneReadingFromEntry(entry_, this);
600 entry_ = NULL;
605 const HttpResponseInfo* HttpCache::Transaction::GetResponseInfo() const {
606 // Null headers means we encountered an error or haven't a response yet
607 if (auth_response_.headers.get())
608 return &auth_response_;
609 return (response_.headers.get() || response_.ssl_info.cert.get() ||
610 response_.cert_request_info.get())
611 ? &response_
612 : NULL;
615 LoadState HttpCache::Transaction::GetLoadState() const {
616 LoadState state = GetWriterLoadState();
617 if (state != LOAD_STATE_WAITING_FOR_CACHE)
618 return state;
620 if (cache_.get())
621 return cache_->GetLoadStateForPendingTransaction(this);
623 return LOAD_STATE_IDLE;
626 UploadProgress HttpCache::Transaction::GetUploadProgress() const {
627 if (network_trans_.get())
628 return network_trans_->GetUploadProgress();
629 return final_upload_progress_;
632 void HttpCache::Transaction::SetQuicServerInfo(
633 QuicServerInfo* quic_server_info) {}
635 bool HttpCache::Transaction::GetLoadTimingInfo(
636 LoadTimingInfo* load_timing_info) const {
637 if (network_trans_)
638 return network_trans_->GetLoadTimingInfo(load_timing_info);
640 if (old_network_trans_load_timing_) {
641 *load_timing_info = *old_network_trans_load_timing_;
642 return true;
645 if (first_cache_access_since_.is_null())
646 return false;
648 // If the cache entry was opened, return that time.
649 load_timing_info->send_start = first_cache_access_since_;
650 // This time doesn't make much sense when reading from the cache, so just use
651 // the same time as send_start.
652 load_timing_info->send_end = first_cache_access_since_;
653 return true;
656 void HttpCache::Transaction::SetPriority(RequestPriority priority) {
657 priority_ = priority;
658 if (network_trans_)
659 network_trans_->SetPriority(priority_);
662 void HttpCache::Transaction::SetWebSocketHandshakeStreamCreateHelper(
663 WebSocketHandshakeStreamBase::CreateHelper* create_helper) {
664 websocket_handshake_stream_base_create_helper_ = create_helper;
665 if (network_trans_)
666 network_trans_->SetWebSocketHandshakeStreamCreateHelper(create_helper);
669 void HttpCache::Transaction::SetBeforeNetworkStartCallback(
670 const BeforeNetworkStartCallback& callback) {
671 DCHECK(!network_trans_);
672 before_network_start_callback_ = callback;
675 void HttpCache::Transaction::SetBeforeProxyHeadersSentCallback(
676 const BeforeProxyHeadersSentCallback& callback) {
677 DCHECK(!network_trans_);
678 before_proxy_headers_sent_callback_ = callback;
681 int HttpCache::Transaction::ResumeNetworkStart() {
682 if (network_trans_)
683 return network_trans_->ResumeNetworkStart();
684 return ERR_UNEXPECTED;
687 //-----------------------------------------------------------------------------
689 void HttpCache::Transaction::DoCallback(int rv) {
690 DCHECK(rv != ERR_IO_PENDING);
691 DCHECK(!callback_.is_null());
693 read_buf_ = NULL; // Release the buffer before invoking the callback.
695 // Since Run may result in Read being called, clear callback_ up front.
696 CompletionCallback c = callback_;
697 callback_.Reset();
698 c.Run(rv);
701 int HttpCache::Transaction::HandleResult(int rv) {
702 DCHECK(rv != ERR_IO_PENDING);
703 if (!callback_.is_null())
704 DoCallback(rv);
706 return rv;
709 // A few common patterns: (Foo* means Foo -> FooComplete)
711 // Not-cached entry:
712 // Start():
713 // GetBackend* -> InitEntry -> OpenEntry* -> CreateEntry* -> AddToEntry* ->
714 // SendRequest* -> SuccessfulSendRequest -> OverwriteCachedResponse ->
715 // CacheWriteResponse* -> TruncateCachedData* -> TruncateCachedMetadata* ->
716 // PartialHeadersReceived
718 // Read():
719 // NetworkRead* -> CacheWriteData*
721 // Cached entry, no validation:
722 // Start():
723 // GetBackend* -> InitEntry -> OpenEntry* -> AddToEntry* -> CacheReadResponse*
724 // -> BeginPartialCacheValidation() -> BeginCacheValidation()
726 // Read():
727 // CacheReadData*
729 // Cached entry, validation (304):
730 // Start():
731 // GetBackend* -> InitEntry -> OpenEntry* -> AddToEntry* -> CacheReadResponse*
732 // -> BeginPartialCacheValidation() -> BeginCacheValidation() ->
733 // SendRequest* -> SuccessfulSendRequest -> UpdateCachedResponse ->
734 // CacheWriteResponse* -> UpdateCachedResponseComplete ->
735 // OverwriteCachedResponse -> PartialHeadersReceived
737 // Read():
738 // CacheReadData*
740 // Cached entry, validation and replace (200):
741 // Start():
742 // GetBackend* -> InitEntry -> OpenEntry* -> AddToEntry* -> CacheReadResponse*
743 // -> BeginPartialCacheValidation() -> BeginCacheValidation() ->
744 // SendRequest* -> SuccessfulSendRequest -> OverwriteCachedResponse ->
745 // CacheWriteResponse* -> DoTruncateCachedData* -> TruncateCachedMetadata* ->
746 // PartialHeadersReceived
748 // Read():
749 // NetworkRead* -> CacheWriteData*
751 // Sparse entry, partially cached, byte range request:
752 // Start():
753 // GetBackend* -> InitEntry -> OpenEntry* -> AddToEntry* -> CacheReadResponse*
754 // -> BeginPartialCacheValidation() -> CacheQueryData* ->
755 // ValidateEntryHeadersAndContinue() -> StartPartialCacheValidation ->
756 // CompletePartialCacheValidation -> BeginCacheValidation() -> SendRequest* ->
757 // SuccessfulSendRequest -> UpdateCachedResponse -> CacheWriteResponse* ->
758 // UpdateCachedResponseComplete -> OverwriteCachedResponse ->
759 // PartialHeadersReceived
761 // Read() 1:
762 // NetworkRead* -> CacheWriteData*
764 // Read() 2:
765 // NetworkRead* -> CacheWriteData* -> StartPartialCacheValidation ->
766 // CompletePartialCacheValidation -> CacheReadData* ->
768 // Read() 3:
769 // CacheReadData* -> StartPartialCacheValidation ->
770 // CompletePartialCacheValidation -> BeginCacheValidation() -> SendRequest* ->
771 // SuccessfulSendRequest -> UpdateCachedResponse* -> OverwriteCachedResponse
772 // -> PartialHeadersReceived -> NetworkRead* -> CacheWriteData*
774 int HttpCache::Transaction::DoLoop(int result) {
775 DCHECK(next_state_ != STATE_NONE);
777 int rv = result;
778 do {
779 State state = next_state_;
780 next_state_ = STATE_NONE;
781 switch (state) {
782 case STATE_GET_BACKEND:
783 DCHECK_EQ(OK, rv);
784 rv = DoGetBackend();
785 break;
786 case STATE_GET_BACKEND_COMPLETE:
787 rv = DoGetBackendComplete(rv);
788 break;
789 case STATE_SEND_REQUEST:
790 DCHECK_EQ(OK, rv);
791 rv = DoSendRequest();
792 break;
793 case STATE_SEND_REQUEST_COMPLETE:
794 rv = DoSendRequestComplete(rv);
795 break;
796 case STATE_SUCCESSFUL_SEND_REQUEST:
797 DCHECK_EQ(OK, rv);
798 rv = DoSuccessfulSendRequest();
799 break;
800 case STATE_NETWORK_READ:
801 DCHECK_EQ(OK, rv);
802 rv = DoNetworkRead();
803 break;
804 case STATE_NETWORK_READ_COMPLETE:
805 rv = DoNetworkReadComplete(rv);
806 break;
807 case STATE_INIT_ENTRY:
808 DCHECK_EQ(OK, rv);
809 rv = DoInitEntry();
810 break;
811 case STATE_OPEN_ENTRY:
812 DCHECK_EQ(OK, rv);
813 rv = DoOpenEntry();
814 break;
815 case STATE_OPEN_ENTRY_COMPLETE:
816 rv = DoOpenEntryComplete(rv);
817 break;
818 case STATE_CREATE_ENTRY:
819 DCHECK_EQ(OK, rv);
820 rv = DoCreateEntry();
821 break;
822 case STATE_CREATE_ENTRY_COMPLETE:
823 rv = DoCreateEntryComplete(rv);
824 break;
825 case STATE_DOOM_ENTRY:
826 DCHECK_EQ(OK, rv);
827 rv = DoDoomEntry();
828 break;
829 case STATE_DOOM_ENTRY_COMPLETE:
830 rv = DoDoomEntryComplete(rv);
831 break;
832 case STATE_ADD_TO_ENTRY:
833 DCHECK_EQ(OK, rv);
834 rv = DoAddToEntry();
835 break;
836 case STATE_ADD_TO_ENTRY_COMPLETE:
837 rv = DoAddToEntryComplete(rv);
838 break;
839 case STATE_START_PARTIAL_CACHE_VALIDATION:
840 DCHECK_EQ(OK, rv);
841 rv = DoStartPartialCacheValidation();
842 break;
843 case STATE_COMPLETE_PARTIAL_CACHE_VALIDATION:
844 rv = DoCompletePartialCacheValidation(rv);
845 break;
846 case STATE_UPDATE_CACHED_RESPONSE:
847 DCHECK_EQ(OK, rv);
848 rv = DoUpdateCachedResponse();
849 break;
850 case STATE_UPDATE_CACHED_RESPONSE_COMPLETE:
851 rv = DoUpdateCachedResponseComplete(rv);
852 break;
853 case STATE_OVERWRITE_CACHED_RESPONSE:
854 DCHECK_EQ(OK, rv);
855 rv = DoOverwriteCachedResponse();
856 break;
857 case STATE_TRUNCATE_CACHED_DATA:
858 DCHECK_EQ(OK, rv);
859 rv = DoTruncateCachedData();
860 break;
861 case STATE_TRUNCATE_CACHED_DATA_COMPLETE:
862 rv = DoTruncateCachedDataComplete(rv);
863 break;
864 case STATE_TRUNCATE_CACHED_METADATA:
865 DCHECK_EQ(OK, rv);
866 rv = DoTruncateCachedMetadata();
867 break;
868 case STATE_TRUNCATE_CACHED_METADATA_COMPLETE:
869 rv = DoTruncateCachedMetadataComplete(rv);
870 break;
871 case STATE_PARTIAL_HEADERS_RECEIVED:
872 DCHECK_EQ(OK, rv);
873 rv = DoPartialHeadersReceived();
874 break;
875 case STATE_CACHE_READ_RESPONSE:
876 DCHECK_EQ(OK, rv);
877 rv = DoCacheReadResponse();
878 break;
879 case STATE_CACHE_READ_RESPONSE_COMPLETE:
880 rv = DoCacheReadResponseComplete(rv);
881 break;
882 case STATE_CACHE_WRITE_RESPONSE:
883 DCHECK_EQ(OK, rv);
884 rv = DoCacheWriteResponse();
885 break;
886 case STATE_CACHE_WRITE_TRUNCATED_RESPONSE:
887 DCHECK_EQ(OK, rv);
888 rv = DoCacheWriteTruncatedResponse();
889 break;
890 case STATE_CACHE_WRITE_RESPONSE_COMPLETE:
891 rv = DoCacheWriteResponseComplete(rv);
892 break;
893 case STATE_CACHE_READ_METADATA:
894 DCHECK_EQ(OK, rv);
895 rv = DoCacheReadMetadata();
896 break;
897 case STATE_CACHE_READ_METADATA_COMPLETE:
898 rv = DoCacheReadMetadataComplete(rv);
899 break;
900 case STATE_CACHE_QUERY_DATA:
901 DCHECK_EQ(OK, rv);
902 rv = DoCacheQueryData();
903 break;
904 case STATE_CACHE_QUERY_DATA_COMPLETE:
905 rv = DoCacheQueryDataComplete(rv);
906 break;
907 case STATE_CACHE_READ_DATA:
908 DCHECK_EQ(OK, rv);
909 rv = DoCacheReadData();
910 break;
911 case STATE_CACHE_READ_DATA_COMPLETE:
912 rv = DoCacheReadDataComplete(rv);
913 break;
914 case STATE_CACHE_WRITE_DATA:
915 rv = DoCacheWriteData(rv);
916 break;
917 case STATE_CACHE_WRITE_DATA_COMPLETE:
918 rv = DoCacheWriteDataComplete(rv);
919 break;
920 default:
921 NOTREACHED() << "bad state";
922 rv = ERR_FAILED;
923 break;
925 } while (rv != ERR_IO_PENDING && next_state_ != STATE_NONE);
927 if (rv != ERR_IO_PENDING)
928 HandleResult(rv);
930 return rv;
933 int HttpCache::Transaction::DoGetBackend() {
934 cache_pending_ = true;
935 next_state_ = STATE_GET_BACKEND_COMPLETE;
936 net_log_.BeginEvent(NetLog::TYPE_HTTP_CACHE_GET_BACKEND);
937 return cache_->GetBackendForTransaction(this);
940 int HttpCache::Transaction::DoGetBackendComplete(int result) {
941 DCHECK(result == OK || result == ERR_FAILED);
942 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_HTTP_CACHE_GET_BACKEND,
943 result);
944 cache_pending_ = false;
946 if (!ShouldPassThrough()) {
947 cache_key_ = cache_->GenerateCacheKey(request_);
949 // Requested cache access mode.
950 if (effective_load_flags_ & LOAD_ONLY_FROM_CACHE) {
951 mode_ = READ;
952 } else if (effective_load_flags_ & LOAD_BYPASS_CACHE) {
953 mode_ = WRITE;
954 } else {
955 mode_ = READ_WRITE;
958 // Downgrade to UPDATE if the request has been externally conditionalized.
959 if (external_validation_.initialized) {
960 if (mode_ & WRITE) {
961 // Strip off the READ_DATA bit (and maybe add back a READ_META bit
962 // in case READ was off).
963 mode_ = UPDATE;
964 } else {
965 mode_ = NONE;
970 // Use PUT and DELETE only to invalidate existing stored entries.
971 if ((request_->method == "PUT" || request_->method == "DELETE") &&
972 mode_ != READ_WRITE && mode_ != WRITE) {
973 mode_ = NONE;
976 // If must use cache, then we must fail. This can happen for back/forward
977 // navigations to a page generated via a form post.
978 if (!(mode_ & READ) && effective_load_flags_ & LOAD_ONLY_FROM_CACHE)
979 return ERR_CACHE_MISS;
981 if (mode_ == NONE) {
982 if (partial_.get()) {
983 partial_->RestoreHeaders(&custom_request_->extra_headers);
984 partial_.reset();
986 next_state_ = STATE_SEND_REQUEST;
987 } else {
988 next_state_ = STATE_INIT_ENTRY;
991 // This is only set if we have something to do with the response.
992 range_requested_ = (partial_.get() != NULL);
994 return OK;
997 int HttpCache::Transaction::DoSendRequest() {
998 DCHECK(mode_ & WRITE || mode_ == NONE);
999 DCHECK(!network_trans_.get());
1001 send_request_since_ = TimeTicks::Now();
1003 // Create a network transaction.
1004 int rv = cache_->network_layer_->CreateTransaction(priority_,
1005 &network_trans_);
1006 if (rv != OK)
1007 return rv;
1008 network_trans_->SetBeforeNetworkStartCallback(before_network_start_callback_);
1009 network_trans_->SetBeforeProxyHeadersSentCallback(
1010 before_proxy_headers_sent_callback_);
1012 // Old load timing information, if any, is now obsolete.
1013 old_network_trans_load_timing_.reset();
1015 if (websocket_handshake_stream_base_create_helper_)
1016 network_trans_->SetWebSocketHandshakeStreamCreateHelper(
1017 websocket_handshake_stream_base_create_helper_);
1019 next_state_ = STATE_SEND_REQUEST_COMPLETE;
1020 rv = network_trans_->Start(request_, io_callback_, net_log_);
1021 return rv;
1024 int HttpCache::Transaction::DoSendRequestComplete(int result) {
1025 if (!cache_.get())
1026 return ERR_UNEXPECTED;
1028 // If requested, and we have a readable cache entry, and we have
1029 // an error indicating that we're offline as opposed to in contact
1030 // with a bad server, read from cache anyway.
1031 if (IsOfflineError(result)) {
1032 if (mode_ == READ_WRITE && entry_ && !partial_) {
1033 RecordOfflineStatus(effective_load_flags_,
1034 OFFLINE_STATUS_DATA_AVAILABLE_OFFLINE);
1035 if (effective_load_flags_ & LOAD_FROM_CACHE_IF_OFFLINE) {
1036 UpdateTransactionPattern(PATTERN_NOT_COVERED);
1037 response_.server_data_unavailable = true;
1038 return SetupEntryForRead();
1040 } else {
1041 RecordOfflineStatus(effective_load_flags_,
1042 OFFLINE_STATUS_DATA_UNAVAILABLE_OFFLINE);
1044 } else {
1045 RecordOfflineStatus(effective_load_flags_,
1046 (result == OK ? OFFLINE_STATUS_NETWORK_SUCCEEDED :
1047 OFFLINE_STATUS_NETWORK_FAILED));
1050 // If we tried to conditionalize the request and failed, we know
1051 // we won't be reading from the cache after this point.
1052 if (couldnt_conditionalize_request_)
1053 mode_ = WRITE;
1055 if (result == OK) {
1056 next_state_ = STATE_SUCCESSFUL_SEND_REQUEST;
1057 return OK;
1060 // Do not record requests that have network errors or restarts.
1061 UpdateTransactionPattern(PATTERN_NOT_COVERED);
1062 if (IsCertificateError(result)) {
1063 const HttpResponseInfo* response = network_trans_->GetResponseInfo();
1064 // If we get a certificate error, then there is a certificate in ssl_info,
1065 // so GetResponseInfo() should never return NULL here.
1066 DCHECK(response);
1067 response_.ssl_info = response->ssl_info;
1068 } else if (result == ERR_SSL_CLIENT_AUTH_CERT_NEEDED) {
1069 const HttpResponseInfo* response = network_trans_->GetResponseInfo();
1070 DCHECK(response);
1071 response_.cert_request_info = response->cert_request_info;
1072 } else if (response_.was_cached) {
1073 DoneWritingToEntry(true);
1075 return result;
1078 // We received the response headers and there is no error.
1079 int HttpCache::Transaction::DoSuccessfulSendRequest() {
1080 DCHECK(!new_response_);
1081 const HttpResponseInfo* new_response = network_trans_->GetResponseInfo();
1082 bool authentication_failure = false;
1084 if (new_response->headers->response_code() == 401 ||
1085 new_response->headers->response_code() == 407) {
1086 auth_response_ = *new_response;
1087 if (!reading_)
1088 return OK;
1090 // We initiated a second request the caller doesn't know about. We should be
1091 // able to authenticate this request because we should have authenticated
1092 // this URL moments ago.
1093 if (IsReadyToRestartForAuth()) {
1094 DCHECK(!response_.auth_challenge.get());
1095 next_state_ = STATE_SEND_REQUEST_COMPLETE;
1096 // In theory we should check to see if there are new cookies, but there
1097 // is no way to do that from here.
1098 return network_trans_->RestartWithAuth(AuthCredentials(), io_callback_);
1101 // We have to perform cleanup at this point so that at least the next
1102 // request can succeed.
1103 authentication_failure = true;
1104 if (entry_)
1105 DoomPartialEntry(false);
1106 mode_ = NONE;
1107 partial_.reset();
1110 new_response_ = new_response;
1111 if (authentication_failure ||
1112 (!ValidatePartialResponse() && !auth_response_.headers.get())) {
1113 // Something went wrong with this request and we have to restart it.
1114 // If we have an authentication response, we are exposed to weird things
1115 // hapenning if the user cancels the authentication before we receive
1116 // the new response.
1117 UpdateTransactionPattern(PATTERN_NOT_COVERED);
1118 response_ = HttpResponseInfo();
1119 ResetNetworkTransaction();
1120 new_response_ = NULL;
1121 next_state_ = STATE_SEND_REQUEST;
1122 return OK;
1125 if (handling_206_ && mode_ == READ_WRITE && !truncated_ && !is_sparse_) {
1126 // We have stored the full entry, but it changed and the server is
1127 // sending a range. We have to delete the old entry.
1128 UpdateTransactionPattern(PATTERN_NOT_COVERED);
1129 DoneWritingToEntry(false);
1132 if (mode_ == WRITE &&
1133 transaction_pattern_ != PATTERN_ENTRY_CANT_CONDITIONALIZE) {
1134 UpdateTransactionPattern(PATTERN_ENTRY_NOT_CACHED);
1137 if (mode_ == WRITE &&
1138 (request_->method == "PUT" || request_->method == "DELETE")) {
1139 if (NonErrorResponse(new_response->headers->response_code())) {
1140 int ret = cache_->DoomEntry(cache_key_, NULL);
1141 DCHECK_EQ(OK, ret);
1143 cache_->DoneWritingToEntry(entry_, true);
1144 entry_ = NULL;
1145 mode_ = NONE;
1148 if (request_->method == "POST" &&
1149 NonErrorResponse(new_response->headers->response_code())) {
1150 cache_->DoomMainEntryForUrl(request_->url);
1153 RecordVaryHeaderHistogram(new_response);
1154 RecordNoStoreHeaderHistogram(request_->load_flags, new_response);
1156 if (new_response_->headers->response_code() == 416 &&
1157 (request_->method == "GET" || request_->method == "POST")) {
1158 // If there is an ective entry it may be destroyed with this transaction.
1159 response_ = *new_response_;
1160 return OK;
1163 // Are we expecting a response to a conditional query?
1164 if (mode_ == READ_WRITE || mode_ == UPDATE) {
1165 if (new_response->headers->response_code() == 304 || handling_206_) {
1166 UpdateTransactionPattern(PATTERN_ENTRY_VALIDATED);
1167 next_state_ = STATE_UPDATE_CACHED_RESPONSE;
1168 return OK;
1170 UpdateTransactionPattern(PATTERN_ENTRY_UPDATED);
1171 mode_ = WRITE;
1174 next_state_ = STATE_OVERWRITE_CACHED_RESPONSE;
1175 return OK;
1178 int HttpCache::Transaction::DoNetworkRead() {
1179 next_state_ = STATE_NETWORK_READ_COMPLETE;
1180 return network_trans_->Read(read_buf_.get(), io_buf_len_, io_callback_);
1183 int HttpCache::Transaction::DoNetworkReadComplete(int result) {
1184 DCHECK(mode_ & WRITE || mode_ == NONE);
1186 if (!cache_.get())
1187 return ERR_UNEXPECTED;
1189 // If there is an error or we aren't saving the data, we are done; just wait
1190 // until the destructor runs to see if we can keep the data.
1191 if (mode_ == NONE || result < 0)
1192 return result;
1194 next_state_ = STATE_CACHE_WRITE_DATA;
1195 return result;
1198 int HttpCache::Transaction::DoInitEntry() {
1199 DCHECK(!new_entry_);
1201 if (!cache_.get())
1202 return ERR_UNEXPECTED;
1204 if (mode_ == WRITE) {
1205 next_state_ = STATE_DOOM_ENTRY;
1206 return OK;
1209 next_state_ = STATE_OPEN_ENTRY;
1210 return OK;
1213 int HttpCache::Transaction::DoOpenEntry() {
1214 DCHECK(!new_entry_);
1215 next_state_ = STATE_OPEN_ENTRY_COMPLETE;
1216 cache_pending_ = true;
1217 net_log_.BeginEvent(NetLog::TYPE_HTTP_CACHE_OPEN_ENTRY);
1218 first_cache_access_since_ = TimeTicks::Now();
1219 return cache_->OpenEntry(cache_key_, &new_entry_, this);
1222 int HttpCache::Transaction::DoOpenEntryComplete(int result) {
1223 // It is important that we go to STATE_ADD_TO_ENTRY whenever the result is
1224 // OK, otherwise the cache will end up with an active entry without any
1225 // transaction attached.
1226 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_HTTP_CACHE_OPEN_ENTRY, result);
1227 cache_pending_ = false;
1228 if (result == OK) {
1229 next_state_ = STATE_ADD_TO_ENTRY;
1230 return OK;
1233 if (result == ERR_CACHE_RACE) {
1234 next_state_ = STATE_INIT_ENTRY;
1235 return OK;
1238 if (request_->method == "PUT" || request_->method == "DELETE") {
1239 DCHECK(mode_ == READ_WRITE || mode_ == WRITE);
1240 mode_ = NONE;
1241 next_state_ = STATE_SEND_REQUEST;
1242 return OK;
1245 if (mode_ == READ_WRITE) {
1246 mode_ = WRITE;
1247 next_state_ = STATE_CREATE_ENTRY;
1248 return OK;
1250 if (mode_ == UPDATE) {
1251 // There is no cache entry to update; proceed without caching.
1252 mode_ = NONE;
1253 next_state_ = STATE_SEND_REQUEST;
1254 return OK;
1256 if (cache_->mode() == PLAYBACK)
1257 DVLOG(1) << "Playback Cache Miss: " << request_->url;
1259 // The entry does not exist, and we are not permitted to create a new entry,
1260 // so we must fail.
1261 return ERR_CACHE_MISS;
1264 int HttpCache::Transaction::DoCreateEntry() {
1265 DCHECK(!new_entry_);
1266 next_state_ = STATE_CREATE_ENTRY_COMPLETE;
1267 cache_pending_ = true;
1268 net_log_.BeginEvent(NetLog::TYPE_HTTP_CACHE_CREATE_ENTRY);
1269 return cache_->CreateEntry(cache_key_, &new_entry_, this);
1272 int HttpCache::Transaction::DoCreateEntryComplete(int result) {
1273 // It is important that we go to STATE_ADD_TO_ENTRY whenever the result is
1274 // OK, otherwise the cache will end up with an active entry without any
1275 // transaction attached.
1276 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_HTTP_CACHE_CREATE_ENTRY,
1277 result);
1278 cache_pending_ = false;
1279 next_state_ = STATE_ADD_TO_ENTRY;
1281 if (result == ERR_CACHE_RACE) {
1282 next_state_ = STATE_INIT_ENTRY;
1283 return OK;
1286 if (result == OK) {
1287 UMA_HISTOGRAM_BOOLEAN("HttpCache.OpenToCreateRace", false);
1288 } else {
1289 UMA_HISTOGRAM_BOOLEAN("HttpCache.OpenToCreateRace", true);
1290 // We have a race here: Maybe we failed to open the entry and decided to
1291 // create one, but by the time we called create, another transaction already
1292 // created the entry. If we want to eliminate this issue, we need an atomic
1293 // OpenOrCreate() method exposed by the disk cache.
1294 DLOG(WARNING) << "Unable to create cache entry";
1295 mode_ = NONE;
1296 if (partial_.get())
1297 partial_->RestoreHeaders(&custom_request_->extra_headers);
1298 next_state_ = STATE_SEND_REQUEST;
1300 return OK;
1303 int HttpCache::Transaction::DoDoomEntry() {
1304 next_state_ = STATE_DOOM_ENTRY_COMPLETE;
1305 cache_pending_ = true;
1306 if (first_cache_access_since_.is_null())
1307 first_cache_access_since_ = TimeTicks::Now();
1308 net_log_.BeginEvent(NetLog::TYPE_HTTP_CACHE_DOOM_ENTRY);
1309 return cache_->DoomEntry(cache_key_, this);
1312 int HttpCache::Transaction::DoDoomEntryComplete(int result) {
1313 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_HTTP_CACHE_DOOM_ENTRY, result);
1314 next_state_ = STATE_CREATE_ENTRY;
1315 cache_pending_ = false;
1316 if (result == ERR_CACHE_RACE)
1317 next_state_ = STATE_INIT_ENTRY;
1318 return OK;
1321 int HttpCache::Transaction::DoAddToEntry() {
1322 DCHECK(new_entry_);
1323 cache_pending_ = true;
1324 next_state_ = STATE_ADD_TO_ENTRY_COMPLETE;
1325 net_log_.BeginEvent(NetLog::TYPE_HTTP_CACHE_ADD_TO_ENTRY);
1326 DCHECK(entry_lock_waiting_since_.is_null());
1327 entry_lock_waiting_since_ = TimeTicks::Now();
1328 int rv = cache_->AddTransactionToEntry(new_entry_, this);
1329 if (rv == ERR_IO_PENDING) {
1330 if (bypass_lock_for_test_) {
1331 OnAddToEntryTimeout(entry_lock_waiting_since_);
1332 } else {
1333 const int kTimeoutSeconds = 20;
1334 base::MessageLoop::current()->PostDelayedTask(
1335 FROM_HERE,
1336 base::Bind(&HttpCache::Transaction::OnAddToEntryTimeout,
1337 weak_factory_.GetWeakPtr(), entry_lock_waiting_since_),
1338 TimeDelta::FromSeconds(kTimeoutSeconds));
1341 return rv;
1344 int HttpCache::Transaction::DoAddToEntryComplete(int result) {
1345 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_HTTP_CACHE_ADD_TO_ENTRY,
1346 result);
1347 const TimeDelta entry_lock_wait =
1348 TimeTicks::Now() - entry_lock_waiting_since_;
1349 UMA_HISTOGRAM_TIMES("HttpCache.EntryLockWait", entry_lock_wait);
1351 entry_lock_waiting_since_ = TimeTicks();
1352 DCHECK(new_entry_);
1353 cache_pending_ = false;
1355 if (result == OK)
1356 entry_ = new_entry_;
1358 // If there is a failure, the cache should have taken care of new_entry_.
1359 new_entry_ = NULL;
1361 if (result == ERR_CACHE_RACE) {
1362 next_state_ = STATE_INIT_ENTRY;
1363 return OK;
1366 if (result == ERR_CACHE_LOCK_TIMEOUT) {
1367 // The cache is busy, bypass it for this transaction.
1368 mode_ = NONE;
1369 next_state_ = STATE_SEND_REQUEST;
1370 if (partial_) {
1371 partial_->RestoreHeaders(&custom_request_->extra_headers);
1372 partial_.reset();
1374 return OK;
1377 if (result != OK) {
1378 NOTREACHED();
1379 return result;
1382 if (mode_ == WRITE) {
1383 if (partial_.get())
1384 partial_->RestoreHeaders(&custom_request_->extra_headers);
1385 next_state_ = STATE_SEND_REQUEST;
1386 } else {
1387 // We have to read the headers from the cached entry.
1388 DCHECK(mode_ & READ_META);
1389 next_state_ = STATE_CACHE_READ_RESPONSE;
1391 return OK;
1394 // We may end up here multiple times for a given request.
1395 int HttpCache::Transaction::DoStartPartialCacheValidation() {
1396 if (mode_ == NONE)
1397 return OK;
1399 next_state_ = STATE_COMPLETE_PARTIAL_CACHE_VALIDATION;
1400 return partial_->ShouldValidateCache(entry_->disk_entry, io_callback_);
1403 int HttpCache::Transaction::DoCompletePartialCacheValidation(int result) {
1404 if (!result) {
1405 // This is the end of the request.
1406 if (mode_ & WRITE) {
1407 DoneWritingToEntry(true);
1408 } else {
1409 cache_->DoneReadingFromEntry(entry_, this);
1410 entry_ = NULL;
1412 return result;
1415 if (result < 0)
1416 return result;
1418 partial_->PrepareCacheValidation(entry_->disk_entry,
1419 &custom_request_->extra_headers);
1421 if (reading_ && partial_->IsCurrentRangeCached()) {
1422 next_state_ = STATE_CACHE_READ_DATA;
1423 return OK;
1426 return BeginCacheValidation();
1429 // We received 304 or 206 and we want to update the cached response headers.
1430 int HttpCache::Transaction::DoUpdateCachedResponse() {
1431 next_state_ = STATE_UPDATE_CACHED_RESPONSE_COMPLETE;
1432 int rv = OK;
1433 // Update cached response based on headers in new_response.
1434 // TODO(wtc): should we update cached certificate (response_.ssl_info), too?
1435 response_.headers->Update(*new_response_->headers.get());
1436 response_.response_time = new_response_->response_time;
1437 response_.request_time = new_response_->request_time;
1438 response_.network_accessed = new_response_->network_accessed;
1440 if (response_.headers->HasHeaderValue("cache-control", "no-store")) {
1441 if (!entry_->doomed) {
1442 int ret = cache_->DoomEntry(cache_key_, NULL);
1443 DCHECK_EQ(OK, ret);
1445 } else {
1446 // If we are already reading, we already updated the headers for this
1447 // request; doing it again will change Content-Length.
1448 if (!reading_) {
1449 target_state_ = STATE_UPDATE_CACHED_RESPONSE_COMPLETE;
1450 next_state_ = STATE_CACHE_WRITE_RESPONSE;
1451 rv = OK;
1454 return rv;
1457 int HttpCache::Transaction::DoUpdateCachedResponseComplete(int result) {
1458 if (mode_ == UPDATE) {
1459 DCHECK(!handling_206_);
1460 // We got a "not modified" response and already updated the corresponding
1461 // cache entry above.
1463 // By closing the cached entry now, we make sure that the 304 rather than
1464 // the cached 200 response, is what will be returned to the user.
1465 DoneWritingToEntry(true);
1466 } else if (entry_ && !handling_206_) {
1467 DCHECK_EQ(READ_WRITE, mode_);
1468 if (!partial_.get() || partial_->IsLastRange()) {
1469 cache_->ConvertWriterToReader(entry_);
1470 mode_ = READ;
1472 // We no longer need the network transaction, so destroy it.
1473 final_upload_progress_ = network_trans_->GetUploadProgress();
1474 ResetNetworkTransaction();
1475 } else if (entry_ && handling_206_ && truncated_ &&
1476 partial_->initial_validation()) {
1477 // We just finished the validation of a truncated entry, and the server
1478 // is willing to resume the operation. Now we go back and start serving
1479 // the first part to the user.
1480 ResetNetworkTransaction();
1481 new_response_ = NULL;
1482 next_state_ = STATE_START_PARTIAL_CACHE_VALIDATION;
1483 partial_->SetRangeToStartDownload();
1484 return OK;
1486 next_state_ = STATE_OVERWRITE_CACHED_RESPONSE;
1487 return OK;
1490 int HttpCache::Transaction::DoOverwriteCachedResponse() {
1491 if (mode_ & READ) {
1492 next_state_ = STATE_PARTIAL_HEADERS_RECEIVED;
1493 return OK;
1496 // We change the value of Content-Length for partial content.
1497 if (handling_206_ && partial_.get())
1498 partial_->FixContentLength(new_response_->headers.get());
1500 response_ = *new_response_;
1502 if (handling_206_ && !CanResume(false)) {
1503 // There is no point in storing this resource because it will never be used.
1504 DoneWritingToEntry(false);
1505 if (partial_.get())
1506 partial_->FixResponseHeaders(response_.headers.get(), true);
1507 next_state_ = STATE_PARTIAL_HEADERS_RECEIVED;
1508 return OK;
1511 target_state_ = STATE_TRUNCATE_CACHED_DATA;
1512 next_state_ = truncated_ ? STATE_CACHE_WRITE_TRUNCATED_RESPONSE :
1513 STATE_CACHE_WRITE_RESPONSE;
1514 return OK;
1517 int HttpCache::Transaction::DoTruncateCachedData() {
1518 next_state_ = STATE_TRUNCATE_CACHED_DATA_COMPLETE;
1519 if (!entry_)
1520 return OK;
1521 if (net_log_.IsLogging())
1522 net_log_.BeginEvent(NetLog::TYPE_HTTP_CACHE_WRITE_DATA);
1523 // Truncate the stream.
1524 return WriteToEntry(kResponseContentIndex, 0, NULL, 0, io_callback_);
1527 int HttpCache::Transaction::DoTruncateCachedDataComplete(int result) {
1528 if (entry_) {
1529 if (net_log_.IsLogging()) {
1530 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_HTTP_CACHE_WRITE_DATA,
1531 result);
1535 next_state_ = STATE_TRUNCATE_CACHED_METADATA;
1536 return OK;
1539 int HttpCache::Transaction::DoTruncateCachedMetadata() {
1540 next_state_ = STATE_TRUNCATE_CACHED_METADATA_COMPLETE;
1541 if (!entry_)
1542 return OK;
1544 if (net_log_.IsLogging())
1545 net_log_.BeginEvent(NetLog::TYPE_HTTP_CACHE_WRITE_INFO);
1546 return WriteToEntry(kMetadataIndex, 0, NULL, 0, io_callback_);
1549 int HttpCache::Transaction::DoTruncateCachedMetadataComplete(int result) {
1550 if (entry_) {
1551 if (net_log_.IsLogging()) {
1552 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_HTTP_CACHE_WRITE_INFO,
1553 result);
1557 next_state_ = STATE_PARTIAL_HEADERS_RECEIVED;
1558 return OK;
1561 int HttpCache::Transaction::DoPartialHeadersReceived() {
1562 new_response_ = NULL;
1563 if (entry_ && !partial_.get() &&
1564 entry_->disk_entry->GetDataSize(kMetadataIndex))
1565 next_state_ = STATE_CACHE_READ_METADATA;
1567 if (!partial_.get())
1568 return OK;
1570 if (reading_) {
1571 if (network_trans_.get()) {
1572 next_state_ = STATE_NETWORK_READ;
1573 } else {
1574 next_state_ = STATE_CACHE_READ_DATA;
1576 } else if (mode_ != NONE) {
1577 // We are about to return the headers for a byte-range request to the user,
1578 // so let's fix them.
1579 partial_->FixResponseHeaders(response_.headers.get(), true);
1581 return OK;
1584 int HttpCache::Transaction::DoCacheReadResponse() {
1585 DCHECK(entry_);
1586 next_state_ = STATE_CACHE_READ_RESPONSE_COMPLETE;
1588 io_buf_len_ = entry_->disk_entry->GetDataSize(kResponseInfoIndex);
1589 read_buf_ = new IOBuffer(io_buf_len_);
1591 net_log_.BeginEvent(NetLog::TYPE_HTTP_CACHE_READ_INFO);
1592 return entry_->disk_entry->ReadData(kResponseInfoIndex, 0, read_buf_.get(),
1593 io_buf_len_, io_callback_);
1596 int HttpCache::Transaction::DoCacheReadResponseComplete(int result) {
1597 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_HTTP_CACHE_READ_INFO, result);
1598 if (result != io_buf_len_ ||
1599 !HttpCache::ParseResponseInfo(read_buf_->data(), io_buf_len_,
1600 &response_, &truncated_)) {
1601 return OnCacheReadError(result, true);
1604 // cert_cache() will be null if the CertCacheTrial field trial is disabled.
1605 if (cache_->cert_cache() && response_.ssl_info.is_valid())
1606 ReadCertChain();
1608 // Some resources may have slipped in as truncated when they're not.
1609 int current_size = entry_->disk_entry->GetDataSize(kResponseContentIndex);
1610 if (response_.headers->GetContentLength() == current_size)
1611 truncated_ = false;
1613 // We now have access to the cache entry.
1615 // o if we are a reader for the transaction, then we can start reading the
1616 // cache entry.
1618 // o if we can read or write, then we should check if the cache entry needs
1619 // to be validated and then issue a network request if needed or just read
1620 // from the cache if the cache entry is already valid.
1622 // o if we are set to UPDATE, then we are handling an externally
1623 // conditionalized request (if-modified-since / if-none-match). We check
1624 // if the request headers define a validation request.
1626 switch (mode_) {
1627 case READ:
1628 UpdateTransactionPattern(PATTERN_ENTRY_USED);
1629 result = BeginCacheRead();
1630 break;
1631 case READ_WRITE:
1632 result = BeginPartialCacheValidation();
1633 break;
1634 case UPDATE:
1635 result = BeginExternallyConditionalizedRequest();
1636 break;
1637 case WRITE:
1638 default:
1639 NOTREACHED();
1640 result = ERR_FAILED;
1642 return result;
1645 int HttpCache::Transaction::DoCacheWriteResponse() {
1646 if (entry_) {
1647 if (net_log_.IsLogging())
1648 net_log_.BeginEvent(NetLog::TYPE_HTTP_CACHE_WRITE_INFO);
1650 return WriteResponseInfoToEntry(false);
1653 int HttpCache::Transaction::DoCacheWriteTruncatedResponse() {
1654 if (entry_) {
1655 if (net_log_.IsLogging())
1656 net_log_.BeginEvent(NetLog::TYPE_HTTP_CACHE_WRITE_INFO);
1658 return WriteResponseInfoToEntry(true);
1661 int HttpCache::Transaction::DoCacheWriteResponseComplete(int result) {
1662 next_state_ = target_state_;
1663 target_state_ = STATE_NONE;
1664 if (!entry_)
1665 return OK;
1666 if (net_log_.IsLogging()) {
1667 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_HTTP_CACHE_WRITE_INFO,
1668 result);
1671 // Balance the AddRef from WriteResponseInfoToEntry.
1672 if (result != io_buf_len_) {
1673 DLOG(ERROR) << "failed to write response info to cache";
1674 DoneWritingToEntry(false);
1676 return OK;
1679 int HttpCache::Transaction::DoCacheReadMetadata() {
1680 DCHECK(entry_);
1681 DCHECK(!response_.metadata.get());
1682 next_state_ = STATE_CACHE_READ_METADATA_COMPLETE;
1684 response_.metadata =
1685 new IOBufferWithSize(entry_->disk_entry->GetDataSize(kMetadataIndex));
1687 net_log_.BeginEvent(NetLog::TYPE_HTTP_CACHE_READ_INFO);
1688 return entry_->disk_entry->ReadData(kMetadataIndex, 0,
1689 response_.metadata.get(),
1690 response_.metadata->size(),
1691 io_callback_);
1694 int HttpCache::Transaction::DoCacheReadMetadataComplete(int result) {
1695 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_HTTP_CACHE_READ_INFO, result);
1696 if (result != response_.metadata->size())
1697 return OnCacheReadError(result, false);
1698 return OK;
1701 int HttpCache::Transaction::DoCacheQueryData() {
1702 next_state_ = STATE_CACHE_QUERY_DATA_COMPLETE;
1703 return entry_->disk_entry->ReadyForSparseIO(io_callback_);
1706 int HttpCache::Transaction::DoCacheQueryDataComplete(int result) {
1707 if (result == ERR_NOT_IMPLEMENTED) {
1708 // Restart the request overwriting the cache entry.
1709 // TODO(pasko): remove this workaround as soon as the SimpleBackendImpl
1710 // supports Sparse IO.
1711 return DoRestartPartialRequest();
1713 DCHECK_EQ(OK, result);
1714 if (!cache_.get())
1715 return ERR_UNEXPECTED;
1717 return ValidateEntryHeadersAndContinue();
1720 int HttpCache::Transaction::DoCacheReadData() {
1721 DCHECK(entry_);
1722 next_state_ = STATE_CACHE_READ_DATA_COMPLETE;
1724 if (net_log_.IsLogging())
1725 net_log_.BeginEvent(NetLog::TYPE_HTTP_CACHE_READ_DATA);
1726 if (partial_.get()) {
1727 return partial_->CacheRead(entry_->disk_entry, read_buf_.get(), io_buf_len_,
1728 io_callback_);
1731 return entry_->disk_entry->ReadData(kResponseContentIndex, read_offset_,
1732 read_buf_.get(), io_buf_len_,
1733 io_callback_);
1736 int HttpCache::Transaction::DoCacheReadDataComplete(int result) {
1737 if (net_log_.IsLogging()) {
1738 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_HTTP_CACHE_READ_DATA,
1739 result);
1742 if (!cache_.get())
1743 return ERR_UNEXPECTED;
1745 if (partial_.get()) {
1746 // Partial requests are confusing to report in histograms because they may
1747 // have multiple underlying requests.
1748 UpdateTransactionPattern(PATTERN_NOT_COVERED);
1749 return DoPartialCacheReadCompleted(result);
1752 if (result > 0) {
1753 read_offset_ += result;
1754 } else if (result == 0) { // End of file.
1755 RecordHistograms();
1756 cache_->DoneReadingFromEntry(entry_, this);
1757 entry_ = NULL;
1758 } else {
1759 return OnCacheReadError(result, false);
1761 return result;
1764 int HttpCache::Transaction::DoCacheWriteData(int num_bytes) {
1765 next_state_ = STATE_CACHE_WRITE_DATA_COMPLETE;
1766 write_len_ = num_bytes;
1767 if (entry_) {
1768 if (net_log_.IsLogging())
1769 net_log_.BeginEvent(NetLog::TYPE_HTTP_CACHE_WRITE_DATA);
1772 return AppendResponseDataToEntry(read_buf_.get(), num_bytes, io_callback_);
1775 int HttpCache::Transaction::DoCacheWriteDataComplete(int result) {
1776 if (entry_) {
1777 if (net_log_.IsLogging()) {
1778 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_HTTP_CACHE_WRITE_DATA,
1779 result);
1782 // Balance the AddRef from DoCacheWriteData.
1783 if (!cache_.get())
1784 return ERR_UNEXPECTED;
1786 if (result != write_len_) {
1787 DLOG(ERROR) << "failed to write response data to cache";
1788 DoneWritingToEntry(false);
1790 // We want to ignore errors writing to disk and just keep reading from
1791 // the network.
1792 result = write_len_;
1793 } else if (!done_reading_ && entry_) {
1794 int current_size = entry_->disk_entry->GetDataSize(kResponseContentIndex);
1795 int64 body_size = response_.headers->GetContentLength();
1796 if (body_size >= 0 && body_size <= current_size)
1797 done_reading_ = true;
1800 if (partial_.get()) {
1801 // This may be the last request.
1802 if (!(result == 0 && !truncated_ &&
1803 (partial_->IsLastRange() || mode_ == WRITE)))
1804 return DoPartialNetworkReadCompleted(result);
1807 if (result == 0) {
1808 // End of file. This may be the result of a connection problem so see if we
1809 // have to keep the entry around to be flagged as truncated later on.
1810 if (done_reading_ || !entry_ || partial_.get() ||
1811 response_.headers->GetContentLength() <= 0)
1812 DoneWritingToEntry(true);
1815 return result;
1818 //-----------------------------------------------------------------------------
1820 void HttpCache::Transaction::ReadCertChain() {
1821 std::string key =
1822 GetCacheKeyForCert(response_.ssl_info.cert->os_cert_handle());
1823 const X509Certificate::OSCertHandles& intermediates =
1824 response_.ssl_info.cert->GetIntermediateCertificates();
1825 int dist_from_root = intermediates.size();
1827 scoped_refptr<SharedChainData> shared_chain_data(
1828 new SharedChainData(intermediates.size() + 1, TimeTicks::Now()));
1829 cache_->cert_cache()->Get(key,
1830 base::Bind(&OnCertReadIOComplete,
1831 dist_from_root,
1832 true /* is leaf */,
1833 shared_chain_data));
1835 for (X509Certificate::OSCertHandles::const_iterator it =
1836 intermediates.begin();
1837 it != intermediates.end();
1838 ++it) {
1839 --dist_from_root;
1840 key = GetCacheKeyForCert(*it);
1841 cache_->cert_cache()->Get(key,
1842 base::Bind(&OnCertReadIOComplete,
1843 dist_from_root,
1844 false /* is not leaf */,
1845 shared_chain_data));
1847 DCHECK_EQ(0, dist_from_root);
1850 void HttpCache::Transaction::WriteCertChain() {
1851 const X509Certificate::OSCertHandles& intermediates =
1852 response_.ssl_info.cert->GetIntermediateCertificates();
1853 int dist_from_root = intermediates.size();
1855 scoped_refptr<SharedChainData> shared_chain_data(
1856 new SharedChainData(intermediates.size() + 1, TimeTicks::Now()));
1857 cache_->cert_cache()->Set(response_.ssl_info.cert->os_cert_handle(),
1858 base::Bind(&OnCertWriteIOComplete,
1859 dist_from_root,
1860 true /* is leaf */,
1861 shared_chain_data));
1862 for (X509Certificate::OSCertHandles::const_iterator it =
1863 intermediates.begin();
1864 it != intermediates.end();
1865 ++it) {
1866 --dist_from_root;
1867 cache_->cert_cache()->Set(*it,
1868 base::Bind(&OnCertWriteIOComplete,
1869 dist_from_root,
1870 false /* is not leaf */,
1871 shared_chain_data));
1873 DCHECK_EQ(0, dist_from_root);
1876 void HttpCache::Transaction::SetRequest(const BoundNetLog& net_log,
1877 const HttpRequestInfo* request) {
1878 net_log_ = net_log;
1879 request_ = request;
1880 effective_load_flags_ = request_->load_flags;
1882 switch (cache_->mode()) {
1883 case NORMAL:
1884 break;
1885 case RECORD:
1886 // When in record mode, we want to NEVER load from the cache.
1887 // The reason for this is beacuse we save the Set-Cookie headers
1888 // (intentionally). If we read from the cache, we replay them
1889 // prematurely.
1890 effective_load_flags_ |= LOAD_BYPASS_CACHE;
1891 break;
1892 case PLAYBACK:
1893 // When in playback mode, we want to load exclusively from the cache.
1894 effective_load_flags_ |= LOAD_ONLY_FROM_CACHE;
1895 break;
1896 case DISABLE:
1897 effective_load_flags_ |= LOAD_DISABLE_CACHE;
1898 break;
1901 // Some headers imply load flags. The order here is significant.
1903 // LOAD_DISABLE_CACHE : no cache read or write
1904 // LOAD_BYPASS_CACHE : no cache read
1905 // LOAD_VALIDATE_CACHE : no cache read unless validation
1907 // The former modes trump latter modes, so if we find a matching header we
1908 // can stop iterating kSpecialHeaders.
1910 static const struct {
1911 const HeaderNameAndValue* search;
1912 int load_flag;
1913 } kSpecialHeaders[] = {
1914 { kPassThroughHeaders, LOAD_DISABLE_CACHE },
1915 { kForceFetchHeaders, LOAD_BYPASS_CACHE },
1916 { kForceValidateHeaders, LOAD_VALIDATE_CACHE },
1919 bool range_found = false;
1920 bool external_validation_error = false;
1922 if (request_->extra_headers.HasHeader(HttpRequestHeaders::kRange))
1923 range_found = true;
1925 for (size_t i = 0; i < ARRAYSIZE_UNSAFE(kSpecialHeaders); ++i) {
1926 if (HeaderMatches(request_->extra_headers, kSpecialHeaders[i].search)) {
1927 effective_load_flags_ |= kSpecialHeaders[i].load_flag;
1928 break;
1932 // Check for conditionalization headers which may correspond with a
1933 // cache validation request.
1934 for (size_t i = 0; i < arraysize(kValidationHeaders); ++i) {
1935 const ValidationHeaderInfo& info = kValidationHeaders[i];
1936 std::string validation_value;
1937 if (request_->extra_headers.GetHeader(
1938 info.request_header_name, &validation_value)) {
1939 if (!external_validation_.values[i].empty() ||
1940 validation_value.empty()) {
1941 external_validation_error = true;
1943 external_validation_.values[i] = validation_value;
1944 external_validation_.initialized = true;
1948 // We don't support ranges and validation headers.
1949 if (range_found && external_validation_.initialized) {
1950 LOG(WARNING) << "Byte ranges AND validation headers found.";
1951 effective_load_flags_ |= LOAD_DISABLE_CACHE;
1954 // If there is more than one validation header, we can't treat this request as
1955 // a cache validation, since we don't know for sure which header the server
1956 // will give us a response for (and they could be contradictory).
1957 if (external_validation_error) {
1958 LOG(WARNING) << "Multiple or malformed validation headers found.";
1959 effective_load_flags_ |= LOAD_DISABLE_CACHE;
1962 if (range_found && !(effective_load_flags_ & LOAD_DISABLE_CACHE)) {
1963 UpdateTransactionPattern(PATTERN_NOT_COVERED);
1964 partial_.reset(new PartialData);
1965 if (request_->method == "GET" && partial_->Init(request_->extra_headers)) {
1966 // We will be modifying the actual range requested to the server, so
1967 // let's remove the header here.
1968 custom_request_.reset(new HttpRequestInfo(*request_));
1969 custom_request_->extra_headers.RemoveHeader(HttpRequestHeaders::kRange);
1970 request_ = custom_request_.get();
1971 partial_->SetHeaders(custom_request_->extra_headers);
1972 } else {
1973 // The range is invalid or we cannot handle it properly.
1974 VLOG(1) << "Invalid byte range found.";
1975 effective_load_flags_ |= LOAD_DISABLE_CACHE;
1976 partial_.reset(NULL);
1981 bool HttpCache::Transaction::ShouldPassThrough() {
1982 // We may have a null disk_cache if there is an error we cannot recover from,
1983 // like not enough disk space, or sharing violations.
1984 if (!cache_->disk_cache_.get())
1985 return true;
1987 // When using the record/playback modes, we always use the cache
1988 // and we never pass through.
1989 if (cache_->mode() == RECORD || cache_->mode() == PLAYBACK)
1990 return false;
1992 if (effective_load_flags_ & LOAD_DISABLE_CACHE)
1993 return true;
1995 if (request_->method == "GET")
1996 return false;
1998 if (request_->method == "POST" && request_->upload_data_stream &&
1999 request_->upload_data_stream->identifier()) {
2000 return false;
2003 if (request_->method == "PUT" && request_->upload_data_stream)
2004 return false;
2006 if (request_->method == "DELETE")
2007 return false;
2009 // TODO(darin): add support for caching HEAD responses
2010 return true;
2013 int HttpCache::Transaction::BeginCacheRead() {
2014 // We don't support any combination of LOAD_ONLY_FROM_CACHE and byte ranges.
2015 if (response_.headers->response_code() == 206 || partial_.get()) {
2016 NOTREACHED();
2017 return ERR_CACHE_MISS;
2020 // We don't have the whole resource.
2021 if (truncated_)
2022 return ERR_CACHE_MISS;
2024 if (entry_->disk_entry->GetDataSize(kMetadataIndex))
2025 next_state_ = STATE_CACHE_READ_METADATA;
2027 return OK;
2030 int HttpCache::Transaction::BeginCacheValidation() {
2031 DCHECK(mode_ == READ_WRITE);
2033 bool skip_validation = !RequiresValidation();
2035 if (truncated_) {
2036 // Truncated entries can cause partial gets, so we shouldn't record this
2037 // load in histograms.
2038 UpdateTransactionPattern(PATTERN_NOT_COVERED);
2039 skip_validation = !partial_->initial_validation();
2042 if (partial_.get() && (is_sparse_ || truncated_) &&
2043 (!partial_->IsCurrentRangeCached() || invalid_range_)) {
2044 // Force revalidation for sparse or truncated entries. Note that we don't
2045 // want to ignore the regular validation logic just because a byte range was
2046 // part of the request.
2047 skip_validation = false;
2050 if (skip_validation) {
2051 UpdateTransactionPattern(PATTERN_ENTRY_USED);
2052 RecordOfflineStatus(effective_load_flags_, OFFLINE_STATUS_FRESH_CACHE);
2053 return SetupEntryForRead();
2054 } else {
2055 // Make the network request conditional, to see if we may reuse our cached
2056 // response. If we cannot do so, then we just resort to a normal fetch.
2057 // Our mode remains READ_WRITE for a conditional request. Even if the
2058 // conditionalization fails, we don't switch to WRITE mode until we
2059 // know we won't be falling back to using the cache entry in the
2060 // LOAD_FROM_CACHE_IF_OFFLINE case.
2061 if (!ConditionalizeRequest()) {
2062 couldnt_conditionalize_request_ = true;
2063 UpdateTransactionPattern(PATTERN_ENTRY_CANT_CONDITIONALIZE);
2064 if (partial_.get())
2065 return DoRestartPartialRequest();
2067 DCHECK_NE(206, response_.headers->response_code());
2069 next_state_ = STATE_SEND_REQUEST;
2071 return OK;
2074 int HttpCache::Transaction::BeginPartialCacheValidation() {
2075 DCHECK(mode_ == READ_WRITE);
2077 if (response_.headers->response_code() != 206 && !partial_.get() &&
2078 !truncated_) {
2079 return BeginCacheValidation();
2082 // Partial requests should not be recorded in histograms.
2083 UpdateTransactionPattern(PATTERN_NOT_COVERED);
2084 if (range_requested_) {
2085 next_state_ = STATE_CACHE_QUERY_DATA;
2086 return OK;
2088 // The request is not for a range, but we have stored just ranges.
2089 partial_.reset(new PartialData());
2090 partial_->SetHeaders(request_->extra_headers);
2091 if (!custom_request_.get()) {
2092 custom_request_.reset(new HttpRequestInfo(*request_));
2093 request_ = custom_request_.get();
2096 return ValidateEntryHeadersAndContinue();
2099 // This should only be called once per request.
2100 int HttpCache::Transaction::ValidateEntryHeadersAndContinue() {
2101 DCHECK(mode_ == READ_WRITE);
2103 if (!partial_->UpdateFromStoredHeaders(
2104 response_.headers.get(), entry_->disk_entry, truncated_)) {
2105 return DoRestartPartialRequest();
2108 if (response_.headers->response_code() == 206)
2109 is_sparse_ = true;
2111 if (!partial_->IsRequestedRangeOK()) {
2112 // The stored data is fine, but the request may be invalid.
2113 invalid_range_ = true;
2116 next_state_ = STATE_START_PARTIAL_CACHE_VALIDATION;
2117 return OK;
2120 int HttpCache::Transaction::BeginExternallyConditionalizedRequest() {
2121 DCHECK_EQ(UPDATE, mode_);
2122 DCHECK(external_validation_.initialized);
2124 for (size_t i = 0; i < arraysize(kValidationHeaders); i++) {
2125 if (external_validation_.values[i].empty())
2126 continue;
2127 // Retrieve either the cached response's "etag" or "last-modified" header.
2128 std::string validator;
2129 response_.headers->EnumerateHeader(
2130 NULL,
2131 kValidationHeaders[i].related_response_header_name,
2132 &validator);
2134 if (response_.headers->response_code() != 200 || truncated_ ||
2135 validator.empty() || validator != external_validation_.values[i]) {
2136 // The externally conditionalized request is not a validation request
2137 // for our existing cache entry. Proceed with caching disabled.
2138 UpdateTransactionPattern(PATTERN_NOT_COVERED);
2139 DoneWritingToEntry(true);
2143 next_state_ = STATE_SEND_REQUEST;
2144 return OK;
2147 int HttpCache::Transaction::RestartNetworkRequest() {
2148 DCHECK(mode_ & WRITE || mode_ == NONE);
2149 DCHECK(network_trans_.get());
2150 DCHECK_EQ(STATE_NONE, next_state_);
2152 next_state_ = STATE_SEND_REQUEST_COMPLETE;
2153 int rv = network_trans_->RestartIgnoringLastError(io_callback_);
2154 if (rv != ERR_IO_PENDING)
2155 return DoLoop(rv);
2156 return rv;
2159 int HttpCache::Transaction::RestartNetworkRequestWithCertificate(
2160 X509Certificate* client_cert) {
2161 DCHECK(mode_ & WRITE || mode_ == NONE);
2162 DCHECK(network_trans_.get());
2163 DCHECK_EQ(STATE_NONE, next_state_);
2165 next_state_ = STATE_SEND_REQUEST_COMPLETE;
2166 int rv = network_trans_->RestartWithCertificate(client_cert, io_callback_);
2167 if (rv != ERR_IO_PENDING)
2168 return DoLoop(rv);
2169 return rv;
2172 int HttpCache::Transaction::RestartNetworkRequestWithAuth(
2173 const AuthCredentials& credentials) {
2174 DCHECK(mode_ & WRITE || mode_ == NONE);
2175 DCHECK(network_trans_.get());
2176 DCHECK_EQ(STATE_NONE, next_state_);
2178 next_state_ = STATE_SEND_REQUEST_COMPLETE;
2179 int rv = network_trans_->RestartWithAuth(credentials, io_callback_);
2180 if (rv != ERR_IO_PENDING)
2181 return DoLoop(rv);
2182 return rv;
2185 bool HttpCache::Transaction::RequiresValidation() {
2186 // TODO(darin): need to do more work here:
2187 // - make sure we have a matching request method
2188 // - watch out for cached responses that depend on authentication
2190 // In playback mode, nothing requires validation.
2191 if (cache_->mode() == net::HttpCache::PLAYBACK)
2192 return false;
2194 if (response_.vary_data.is_valid() &&
2195 !response_.vary_data.MatchesRequest(*request_,
2196 *response_.headers.get())) {
2197 vary_mismatch_ = true;
2198 return true;
2201 if (effective_load_flags_ & LOAD_PREFERRING_CACHE)
2202 return false;
2204 if (effective_load_flags_ & LOAD_VALIDATE_CACHE)
2205 return true;
2207 if (request_->method == "PUT" || request_->method == "DELETE")
2208 return true;
2210 if (response_.headers->RequiresValidation(
2211 response_.request_time, response_.response_time, Time::Now())) {
2212 return true;
2215 return false;
2218 bool HttpCache::Transaction::ConditionalizeRequest() {
2219 DCHECK(response_.headers.get());
2221 if (request_->method == "PUT" || request_->method == "DELETE")
2222 return false;
2224 // This only makes sense for cached 200 or 206 responses.
2225 if (response_.headers->response_code() != 200 &&
2226 response_.headers->response_code() != 206) {
2227 return false;
2230 // We should have handled this case before.
2231 DCHECK(response_.headers->response_code() != 206 ||
2232 response_.headers->HasStrongValidators());
2234 // Just use the first available ETag and/or Last-Modified header value.
2235 // TODO(darin): Or should we use the last?
2237 std::string etag_value;
2238 if (response_.headers->GetHttpVersion() >= HttpVersion(1, 1))
2239 response_.headers->EnumerateHeader(NULL, "etag", &etag_value);
2241 std::string last_modified_value;
2242 if (!vary_mismatch_) {
2243 response_.headers->EnumerateHeader(NULL, "last-modified",
2244 &last_modified_value);
2247 if (etag_value.empty() && last_modified_value.empty())
2248 return false;
2250 if (!partial_.get()) {
2251 // Need to customize the request, so this forces us to allocate :(
2252 custom_request_.reset(new HttpRequestInfo(*request_));
2253 request_ = custom_request_.get();
2255 DCHECK(custom_request_.get());
2257 bool use_if_range = partial_.get() && !partial_->IsCurrentRangeCached() &&
2258 !invalid_range_;
2260 if (!etag_value.empty()) {
2261 if (use_if_range) {
2262 // We don't want to switch to WRITE mode if we don't have this block of a
2263 // byte-range request because we may have other parts cached.
2264 custom_request_->extra_headers.SetHeader(
2265 HttpRequestHeaders::kIfRange, etag_value);
2266 } else {
2267 custom_request_->extra_headers.SetHeader(
2268 HttpRequestHeaders::kIfNoneMatch, etag_value);
2270 // For byte-range requests, make sure that we use only one way to validate
2271 // the request.
2272 if (partial_.get() && !partial_->IsCurrentRangeCached())
2273 return true;
2276 if (!last_modified_value.empty()) {
2277 if (use_if_range) {
2278 custom_request_->extra_headers.SetHeader(
2279 HttpRequestHeaders::kIfRange, last_modified_value);
2280 } else {
2281 custom_request_->extra_headers.SetHeader(
2282 HttpRequestHeaders::kIfModifiedSince, last_modified_value);
2286 return true;
2289 // We just received some headers from the server. We may have asked for a range,
2290 // in which case partial_ has an object. This could be the first network request
2291 // we make to fulfill the original request, or we may be already reading (from
2292 // the net and / or the cache). If we are not expecting a certain response, we
2293 // just bypass the cache for this request (but again, maybe we are reading), and
2294 // delete partial_ (so we are not able to "fix" the headers that we return to
2295 // the user). This results in either a weird response for the caller (we don't
2296 // expect it after all), or maybe a range that was not exactly what it was asked
2297 // for.
2299 // If the server is simply telling us that the resource has changed, we delete
2300 // the cached entry and restart the request as the caller intended (by returning
2301 // false from this method). However, we may not be able to do that at any point,
2302 // for instance if we already returned the headers to the user.
2304 // WARNING: Whenever this code returns false, it has to make sure that the next
2305 // time it is called it will return true so that we don't keep retrying the
2306 // request.
2307 bool HttpCache::Transaction::ValidatePartialResponse() {
2308 const HttpResponseHeaders* headers = new_response_->headers.get();
2309 int response_code = headers->response_code();
2310 bool partial_response = (response_code == 206);
2311 handling_206_ = false;
2313 if (!entry_ || request_->method != "GET")
2314 return true;
2316 if (invalid_range_) {
2317 // We gave up trying to match this request with the stored data. If the
2318 // server is ok with the request, delete the entry, otherwise just ignore
2319 // this request
2320 DCHECK(!reading_);
2321 if (partial_response || response_code == 200) {
2322 DoomPartialEntry(true);
2323 mode_ = NONE;
2324 } else {
2325 if (response_code == 304)
2326 FailRangeRequest();
2327 IgnoreRangeRequest();
2329 return true;
2332 if (!partial_.get()) {
2333 // We are not expecting 206 but we may have one.
2334 if (partial_response)
2335 IgnoreRangeRequest();
2337 return true;
2340 // TODO(rvargas): Do we need to consider other results here?.
2341 bool failure = response_code == 200 || response_code == 416;
2343 if (partial_->IsCurrentRangeCached()) {
2344 // We asked for "If-None-Match: " so a 206 means a new object.
2345 if (partial_response)
2346 failure = true;
2348 if (response_code == 304 && partial_->ResponseHeadersOK(headers))
2349 return true;
2350 } else {
2351 // We asked for "If-Range: " so a 206 means just another range.
2352 if (partial_response && partial_->ResponseHeadersOK(headers)) {
2353 handling_206_ = true;
2354 return true;
2357 if (!reading_ && !is_sparse_ && !partial_response) {
2358 // See if we can ignore the fact that we issued a byte range request.
2359 // If the server sends 200, just store it. If it sends an error, redirect
2360 // or something else, we may store the response as long as we didn't have
2361 // anything already stored.
2362 if (response_code == 200 ||
2363 (!truncated_ && response_code != 304 && response_code != 416)) {
2364 // The server is sending something else, and we can save it.
2365 DCHECK((truncated_ && !partial_->IsLastRange()) || range_requested_);
2366 partial_.reset();
2367 truncated_ = false;
2368 return true;
2372 // 304 is not expected here, but we'll spare the entry (unless it was
2373 // truncated).
2374 if (truncated_)
2375 failure = true;
2378 if (failure) {
2379 // We cannot truncate this entry, it has to be deleted.
2380 UpdateTransactionPattern(PATTERN_NOT_COVERED);
2381 DoomPartialEntry(false);
2382 mode_ = NONE;
2383 if (!reading_ && !partial_->IsLastRange()) {
2384 // We'll attempt to issue another network request, this time without us
2385 // messing up the headers.
2386 partial_->RestoreHeaders(&custom_request_->extra_headers);
2387 partial_.reset();
2388 truncated_ = false;
2389 return false;
2391 LOG(WARNING) << "Failed to revalidate partial entry";
2392 partial_.reset();
2393 return true;
2396 IgnoreRangeRequest();
2397 return true;
2400 void HttpCache::Transaction::IgnoreRangeRequest() {
2401 // We have a problem. We may or may not be reading already (in which case we
2402 // returned the headers), but we'll just pretend that this request is not
2403 // using the cache and see what happens. Most likely this is the first
2404 // response from the server (it's not changing its mind midway, right?).
2405 UpdateTransactionPattern(PATTERN_NOT_COVERED);
2406 if (mode_ & WRITE)
2407 DoneWritingToEntry(mode_ != WRITE);
2408 else if (mode_ & READ && entry_)
2409 cache_->DoneReadingFromEntry(entry_, this);
2411 partial_.reset(NULL);
2412 entry_ = NULL;
2413 mode_ = NONE;
2416 void HttpCache::Transaction::FailRangeRequest() {
2417 response_ = *new_response_;
2418 partial_->FixResponseHeaders(response_.headers.get(), false);
2421 int HttpCache::Transaction::SetupEntryForRead() {
2422 if (network_trans_)
2423 ResetNetworkTransaction();
2424 if (partial_.get()) {
2425 if (truncated_ || is_sparse_ || !invalid_range_) {
2426 // We are going to return the saved response headers to the caller, so
2427 // we may need to adjust them first.
2428 next_state_ = STATE_PARTIAL_HEADERS_RECEIVED;
2429 return OK;
2430 } else {
2431 partial_.reset();
2434 cache_->ConvertWriterToReader(entry_);
2435 mode_ = READ;
2437 if (entry_->disk_entry->GetDataSize(kMetadataIndex))
2438 next_state_ = STATE_CACHE_READ_METADATA;
2439 return OK;
2443 int HttpCache::Transaction::ReadFromNetwork(IOBuffer* data, int data_len) {
2444 read_buf_ = data;
2445 io_buf_len_ = data_len;
2446 next_state_ = STATE_NETWORK_READ;
2447 return DoLoop(OK);
2450 int HttpCache::Transaction::ReadFromEntry(IOBuffer* data, int data_len) {
2451 read_buf_ = data;
2452 io_buf_len_ = data_len;
2453 next_state_ = STATE_CACHE_READ_DATA;
2454 return DoLoop(OK);
2457 int HttpCache::Transaction::WriteToEntry(int index, int offset,
2458 IOBuffer* data, int data_len,
2459 const CompletionCallback& callback) {
2460 if (!entry_)
2461 return data_len;
2463 int rv = 0;
2464 if (!partial_.get() || !data_len) {
2465 rv = entry_->disk_entry->WriteData(index, offset, data, data_len, callback,
2466 true);
2467 } else {
2468 rv = partial_->CacheWrite(entry_->disk_entry, data, data_len, callback);
2470 return rv;
2473 int HttpCache::Transaction::WriteResponseInfoToEntry(bool truncated) {
2474 next_state_ = STATE_CACHE_WRITE_RESPONSE_COMPLETE;
2475 if (!entry_)
2476 return OK;
2478 // Do not cache no-store content (unless we are record mode). Do not cache
2479 // content with cert errors either. This is to prevent not reporting net
2480 // errors when loading a resource from the cache. When we load a page over
2481 // HTTPS with a cert error we show an SSL blocking page. If the user clicks
2482 // proceed we reload the resource ignoring the errors. The loaded resource
2483 // is then cached. If that resource is subsequently loaded from the cache,
2484 // no net error is reported (even though the cert status contains the actual
2485 // errors) and no SSL blocking page is shown. An alternative would be to
2486 // reverse-map the cert status to a net error and replay the net error.
2487 if ((cache_->mode() != RECORD &&
2488 response_.headers->HasHeaderValue("cache-control", "no-store")) ||
2489 net::IsCertStatusError(response_.ssl_info.cert_status)) {
2490 DoneWritingToEntry(false);
2491 if (net_log_.IsLogging())
2492 net_log_.EndEvent(NetLog::TYPE_HTTP_CACHE_WRITE_INFO);
2493 return OK;
2496 // cert_cache() will be null if the CertCacheTrial field trial is disabled.
2497 if (cache_->cert_cache() && response_.ssl_info.is_valid())
2498 WriteCertChain();
2500 // When writing headers, we normally only write the non-transient
2501 // headers; when in record mode, record everything.
2502 bool skip_transient_headers = (cache_->mode() != RECORD);
2504 if (truncated)
2505 DCHECK_EQ(200, response_.headers->response_code());
2507 scoped_refptr<PickledIOBuffer> data(new PickledIOBuffer());
2508 response_.Persist(data->pickle(), skip_transient_headers, truncated);
2509 data->Done();
2511 io_buf_len_ = data->pickle()->size();
2512 return entry_->disk_entry->WriteData(kResponseInfoIndex, 0, data.get(),
2513 io_buf_len_, io_callback_, true);
2516 int HttpCache::Transaction::AppendResponseDataToEntry(
2517 IOBuffer* data, int data_len, const CompletionCallback& callback) {
2518 if (!entry_ || !data_len)
2519 return data_len;
2521 int current_size = entry_->disk_entry->GetDataSize(kResponseContentIndex);
2522 return WriteToEntry(kResponseContentIndex, current_size, data, data_len,
2523 callback);
2526 void HttpCache::Transaction::DoneWritingToEntry(bool success) {
2527 if (!entry_)
2528 return;
2530 RecordHistograms();
2532 cache_->DoneWritingToEntry(entry_, success);
2533 entry_ = NULL;
2534 mode_ = NONE; // switch to 'pass through' mode
2537 int HttpCache::Transaction::OnCacheReadError(int result, bool restart) {
2538 DLOG(ERROR) << "ReadData failed: " << result;
2539 const int result_for_histogram = std::max(0, -result);
2540 if (restart) {
2541 UMA_HISTOGRAM_SPARSE_SLOWLY("HttpCache.ReadErrorRestartable",
2542 result_for_histogram);
2543 } else {
2544 UMA_HISTOGRAM_SPARSE_SLOWLY("HttpCache.ReadErrorNonRestartable",
2545 result_for_histogram);
2548 // Avoid using this entry in the future.
2549 if (cache_.get())
2550 cache_->DoomActiveEntry(cache_key_);
2552 if (restart) {
2553 DCHECK(!reading_);
2554 DCHECK(!network_trans_.get());
2555 cache_->DoneWithEntry(entry_, this, false);
2556 entry_ = NULL;
2557 is_sparse_ = false;
2558 partial_.reset();
2559 next_state_ = STATE_GET_BACKEND;
2560 return OK;
2563 return ERR_CACHE_READ_FAILURE;
2566 void HttpCache::Transaction::OnAddToEntryTimeout(base::TimeTicks start_time) {
2567 if (entry_lock_waiting_since_ != start_time)
2568 return;
2570 DCHECK_EQ(next_state_, STATE_ADD_TO_ENTRY_COMPLETE);
2572 if (!cache_)
2573 return;
2575 cache_->RemovePendingTransaction(this);
2576 OnIOComplete(ERR_CACHE_LOCK_TIMEOUT);
2579 void HttpCache::Transaction::DoomPartialEntry(bool delete_object) {
2580 DVLOG(2) << "DoomPartialEntry";
2581 int rv = cache_->DoomEntry(cache_key_, NULL);
2582 DCHECK_EQ(OK, rv);
2583 cache_->DoneWithEntry(entry_, this, false);
2584 entry_ = NULL;
2585 is_sparse_ = false;
2586 if (delete_object)
2587 partial_.reset(NULL);
2590 int HttpCache::Transaction::DoPartialNetworkReadCompleted(int result) {
2591 partial_->OnNetworkReadCompleted(result);
2593 if (result == 0) {
2594 // We need to move on to the next range.
2595 ResetNetworkTransaction();
2596 next_state_ = STATE_START_PARTIAL_CACHE_VALIDATION;
2598 return result;
2601 int HttpCache::Transaction::DoPartialCacheReadCompleted(int result) {
2602 partial_->OnCacheReadCompleted(result);
2604 if (result == 0 && mode_ == READ_WRITE) {
2605 // We need to move on to the next range.
2606 next_state_ = STATE_START_PARTIAL_CACHE_VALIDATION;
2607 } else if (result < 0) {
2608 return OnCacheReadError(result, false);
2610 return result;
2613 int HttpCache::Transaction::DoRestartPartialRequest() {
2614 // The stored data cannot be used. Get rid of it and restart this request.
2615 // We need to also reset the |truncated_| flag as a new entry is created.
2616 DoomPartialEntry(!range_requested_);
2617 mode_ = WRITE;
2618 truncated_ = false;
2619 next_state_ = STATE_INIT_ENTRY;
2620 return OK;
2623 void HttpCache::Transaction::ResetNetworkTransaction() {
2624 DCHECK(!old_network_trans_load_timing_);
2625 DCHECK(network_trans_);
2626 LoadTimingInfo load_timing;
2627 if (network_trans_->GetLoadTimingInfo(&load_timing))
2628 old_network_trans_load_timing_.reset(new LoadTimingInfo(load_timing));
2629 total_received_bytes_ += network_trans_->GetTotalReceivedBytes();
2630 network_trans_.reset();
2633 // Histogram data from the end of 2010 show the following distribution of
2634 // response headers:
2636 // Content-Length............... 87%
2637 // Date......................... 98%
2638 // Last-Modified................ 49%
2639 // Etag......................... 19%
2640 // Accept-Ranges: bytes......... 25%
2641 // Accept-Ranges: none.......... 0.4%
2642 // Strong Validator............. 50%
2643 // Strong Validator + ranges.... 24%
2644 // Strong Validator + CL........ 49%
2646 bool HttpCache::Transaction::CanResume(bool has_data) {
2647 // Double check that there is something worth keeping.
2648 if (has_data && !entry_->disk_entry->GetDataSize(kResponseContentIndex))
2649 return false;
2651 if (request_->method != "GET")
2652 return false;
2654 // Note that if this is a 206, content-length was already fixed after calling
2655 // PartialData::ResponseHeadersOK().
2656 if (response_.headers->GetContentLength() <= 0 ||
2657 response_.headers->HasHeaderValue("Accept-Ranges", "none") ||
2658 !response_.headers->HasStrongValidators()) {
2659 return false;
2662 return true;
2665 void HttpCache::Transaction::UpdateTransactionPattern(
2666 TransactionPattern new_transaction_pattern) {
2667 if (transaction_pattern_ == PATTERN_NOT_COVERED)
2668 return;
2669 DCHECK(transaction_pattern_ == PATTERN_UNDEFINED ||
2670 new_transaction_pattern == PATTERN_NOT_COVERED);
2671 transaction_pattern_ = new_transaction_pattern;
2674 void HttpCache::Transaction::RecordHistograms() {
2675 DCHECK_NE(PATTERN_UNDEFINED, transaction_pattern_);
2676 if (!cache_.get() || !cache_->GetCurrentBackend() ||
2677 cache_->GetCurrentBackend()->GetCacheType() != DISK_CACHE ||
2678 cache_->mode() != NORMAL || request_->method != "GET") {
2679 return;
2681 UMA_HISTOGRAM_ENUMERATION(
2682 "HttpCache.Pattern", transaction_pattern_, PATTERN_MAX);
2683 if (transaction_pattern_ == PATTERN_NOT_COVERED)
2684 return;
2685 DCHECK(!range_requested_);
2686 DCHECK(!first_cache_access_since_.is_null());
2688 TimeDelta total_time = base::TimeTicks::Now() - first_cache_access_since_;
2690 UMA_HISTOGRAM_TIMES("HttpCache.AccessToDone", total_time);
2692 bool did_send_request = !send_request_since_.is_null();
2693 DCHECK(
2694 (did_send_request &&
2695 (transaction_pattern_ == PATTERN_ENTRY_NOT_CACHED ||
2696 transaction_pattern_ == PATTERN_ENTRY_VALIDATED ||
2697 transaction_pattern_ == PATTERN_ENTRY_UPDATED ||
2698 transaction_pattern_ == PATTERN_ENTRY_CANT_CONDITIONALIZE)) ||
2699 (!did_send_request && transaction_pattern_ == PATTERN_ENTRY_USED));
2701 if (!did_send_request) {
2702 DCHECK(transaction_pattern_ == PATTERN_ENTRY_USED);
2703 UMA_HISTOGRAM_TIMES("HttpCache.AccessToDone.Used", total_time);
2704 return;
2707 TimeDelta before_send_time = send_request_since_ - first_cache_access_since_;
2708 int before_send_percent =
2709 total_time.ToInternalValue() == 0 ? 0
2710 : before_send_time * 100 / total_time;
2711 DCHECK_LE(0, before_send_percent);
2712 DCHECK_GE(100, before_send_percent);
2714 UMA_HISTOGRAM_TIMES("HttpCache.AccessToDone.SentRequest", total_time);
2715 UMA_HISTOGRAM_TIMES("HttpCache.BeforeSend", before_send_time);
2716 UMA_HISTOGRAM_PERCENTAGE("HttpCache.PercentBeforeSend", before_send_percent);
2718 // TODO(gavinp): Remove or minimize these histograms, particularly the ones
2719 // below this comment after we have received initial data.
2720 switch (transaction_pattern_) {
2721 case PATTERN_ENTRY_CANT_CONDITIONALIZE: {
2722 UMA_HISTOGRAM_TIMES("HttpCache.BeforeSend.CantConditionalize",
2723 before_send_time);
2724 UMA_HISTOGRAM_PERCENTAGE("HttpCache.PercentBeforeSend.CantConditionalize",
2725 before_send_percent);
2726 break;
2728 case PATTERN_ENTRY_NOT_CACHED: {
2729 UMA_HISTOGRAM_TIMES("HttpCache.BeforeSend.NotCached", before_send_time);
2730 UMA_HISTOGRAM_PERCENTAGE("HttpCache.PercentBeforeSend.NotCached",
2731 before_send_percent);
2732 break;
2734 case PATTERN_ENTRY_VALIDATED: {
2735 UMA_HISTOGRAM_TIMES("HttpCache.BeforeSend.Validated", before_send_time);
2736 UMA_HISTOGRAM_PERCENTAGE("HttpCache.PercentBeforeSend.Validated",
2737 before_send_percent);
2738 break;
2740 case PATTERN_ENTRY_UPDATED: {
2741 UMA_HISTOGRAM_TIMES("HttpCache.BeforeSend.Updated", before_send_time);
2742 UMA_HISTOGRAM_PERCENTAGE("HttpCache.PercentBeforeSend.Updated",
2743 before_send_percent);
2744 break;
2746 default:
2747 NOTREACHED();
2751 void HttpCache::Transaction::OnIOComplete(int result) {
2752 DoLoop(result);
2755 } // namespace net