Update To 11.40.268.0
[platform/framework/web/crosswalk.git] / src / net / http / http_cache_transaction.cc
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.
4
5 #include "net/http/http_cache_transaction.h"
6
7 #include "build/build_config.h"
8
9 #if defined(OS_POSIX)
10 #include <unistd.h>
11 #endif
12
13 #include <algorithm>
14 #include <string>
15
16 #include "base/bind.h"
17 #include "base/compiler_specific.h"
18 #include "base/format_macros.h"
19 #include "base/memory/ref_counted.h"
20 #include "base/memory/scoped_ptr.h"
21 #include "base/metrics/field_trial.h"
22 #include "base/metrics/histogram.h"
23 #include "base/metrics/sparse_histogram.h"
24 #include "base/profiler/scoped_tracker.h"
25 #include "base/rand_util.h"
26 #include "base/strings/string_number_conversions.h"
27 #include "base/strings/string_piece.h"
28 #include "base/strings/string_util.h"
29 #include "base/strings/stringprintf.h"
30 #include "base/time/time.h"
31 #include "base/values.h"
32 #include "net/base/completion_callback.h"
33 #include "net/base/io_buffer.h"
34 #include "net/base/load_flags.h"
35 #include "net/base/load_timing_info.h"
36 #include "net/base/net_errors.h"
37 #include "net/base/net_log.h"
38 #include "net/base/upload_data_stream.h"
39 #include "net/cert/cert_status_flags.h"
40 #include "net/disk_cache/disk_cache.h"
41 #include "net/http/disk_based_cert_cache.h"
42 #include "net/http/http_network_session.h"
43 #include "net/http/http_request_info.h"
44 #include "net/http/http_response_headers.h"
45 #include "net/http/http_transaction.h"
46 #include "net/http/http_util.h"
47 #include "net/http/partial_data.h"
48 #include "net/ssl/ssl_cert_request_info.h"
49 #include "net/ssl/ssl_config_service.h"
50
51 using base::Time;
52 using base::TimeDelta;
53 using base::TimeTicks;
54
55 namespace {
56
57 // TODO(ricea): Move this to HttpResponseHeaders once it is standardised.
58 static const char kFreshnessHeader[] = "Resource-Freshness";
59
60 // Stores data relevant to the statistics of writing and reading entire
61 // certificate chains using DiskBasedCertCache. |num_pending_ops| is the number
62 // of certificates in the chain that have pending operations in the
63 // DiskBasedCertCache. |start_time| is the time that the read and write
64 // commands began being issued to the DiskBasedCertCache.
65 // TODO(brandonsalmon): Remove this when it is no longer necessary to
66 // collect data.
67 class SharedChainData : public base::RefCounted<SharedChainData> {
68  public:
69   SharedChainData(int num_ops, TimeTicks start)
70       : num_pending_ops(num_ops), start_time(start) {}
71
72   int num_pending_ops;
73   TimeTicks start_time;
74
75  private:
76   friend class base::RefCounted<SharedChainData>;
77   ~SharedChainData() {}
78   DISALLOW_COPY_AND_ASSIGN(SharedChainData);
79 };
80
81 // Used to obtain a cache entry key for an OSCertHandle.
82 // TODO(brandonsalmon): Remove this when cache keys are stored
83 // and no longer have to be recomputed to retrieve the OSCertHandle
84 // from the disk.
85 std::string GetCacheKeyForCert(net::X509Certificate::OSCertHandle cert_handle) {
86   net::SHA1HashValue fingerprint =
87       net::X509Certificate::CalculateFingerprint(cert_handle);
88
89   return "cert:" +
90          base::HexEncode(fingerprint.data, arraysize(fingerprint.data));
91 }
92
93 // |dist_from_root| indicates the position of the read certificate in the
94 // certificate chain, 0 indicating it is the root. |is_leaf| indicates
95 // whether or not the read certificate was the leaf of the chain.
96 // |shared_chain_data| contains data shared by each certificate in
97 // the chain.
98 void OnCertReadIOComplete(
99     int dist_from_root,
100     bool is_leaf,
101     const scoped_refptr<SharedChainData>& shared_chain_data,
102     net::X509Certificate::OSCertHandle cert_handle) {
103   // If |num_pending_ops| is one, this was the last pending read operation
104   // for this chain of certificates. The total time used to read the chain
105   // can be calculated by subtracting the starting time from Now().
106   shared_chain_data->num_pending_ops--;
107   if (!shared_chain_data->num_pending_ops) {
108     const TimeDelta read_chain_wait =
109         TimeTicks::Now() - shared_chain_data->start_time;
110     UMA_HISTOGRAM_CUSTOM_TIMES("DiskBasedCertCache.ChainReadTime",
111                                read_chain_wait,
112                                base::TimeDelta::FromMilliseconds(1),
113                                base::TimeDelta::FromMinutes(10),
114                                50);
115   }
116
117   bool success = (cert_handle != NULL);
118   if (is_leaf)
119     UMA_HISTOGRAM_BOOLEAN("DiskBasedCertCache.CertIoReadSuccessLeaf", success);
120
121   if (success)
122     UMA_HISTOGRAM_CUSTOM_COUNTS(
123         "DiskBasedCertCache.CertIoReadSuccess", dist_from_root, 0, 10, 7);
124   else
125     UMA_HISTOGRAM_CUSTOM_COUNTS(
126         "DiskBasedCertCache.CertIoReadFailure", dist_from_root, 0, 10, 7);
127 }
128
129 // |dist_from_root| indicates the position of the written certificate in the
130 // certificate chain, 0 indicating it is the root. |is_leaf| indicates
131 // whether or not the written certificate was the leaf of the chain.
132 // |shared_chain_data| contains data shared by each certificate in
133 // the chain.
134 void OnCertWriteIOComplete(
135     int dist_from_root,
136     bool is_leaf,
137     const scoped_refptr<SharedChainData>& shared_chain_data,
138     const std::string& key) {
139   // If |num_pending_ops| is one, this was the last pending write operation
140   // for this chain of certificates. The total time used to write the chain
141   // can be calculated by subtracting the starting time from Now().
142   shared_chain_data->num_pending_ops--;
143   if (!shared_chain_data->num_pending_ops) {
144     const TimeDelta write_chain_wait =
145         TimeTicks::Now() - shared_chain_data->start_time;
146     UMA_HISTOGRAM_CUSTOM_TIMES("DiskBasedCertCache.ChainWriteTime",
147                                write_chain_wait,
148                                base::TimeDelta::FromMilliseconds(1),
149                                base::TimeDelta::FromMinutes(10),
150                                50);
151   }
152
153   bool success = !key.empty();
154   if (is_leaf)
155     UMA_HISTOGRAM_BOOLEAN("DiskBasedCertCache.CertIoWriteSuccessLeaf", success);
156
157   if (success)
158     UMA_HISTOGRAM_CUSTOM_COUNTS(
159         "DiskBasedCertCache.CertIoWriteSuccess", dist_from_root, 0, 10, 7);
160   else
161     UMA_HISTOGRAM_CUSTOM_COUNTS(
162         "DiskBasedCertCache.CertIoWriteFailure", dist_from_root, 0, 10, 7);
163 }
164
165 // From http://tools.ietf.org/html/draft-ietf-httpbis-p6-cache-21#section-6
166 //      a "non-error response" is one with a 2xx (Successful) or 3xx
167 //      (Redirection) status code.
168 bool NonErrorResponse(int status_code) {
169   int status_code_range = status_code / 100;
170   return status_code_range == 2 || status_code_range == 3;
171 }
172
173 // Error codes that will be considered indicative of a page being offline/
174 // unreachable for LOAD_FROM_CACHE_IF_OFFLINE.
175 bool IsOfflineError(int error) {
176   return (error == net::ERR_NAME_NOT_RESOLVED ||
177           error == net::ERR_INTERNET_DISCONNECTED ||
178           error == net::ERR_ADDRESS_UNREACHABLE ||
179           error == net::ERR_CONNECTION_TIMED_OUT);
180 }
181
182 // Enum for UMA, indicating the status (with regard to offline mode) of
183 // a particular request.
184 enum RequestOfflineStatus {
185   // A cache transaction hit in cache (data was present and not stale)
186   // and returned it.
187   OFFLINE_STATUS_FRESH_CACHE,
188
189   // A network request was required for a cache entry, and it succeeded.
190   OFFLINE_STATUS_NETWORK_SUCCEEDED,
191
192   // A network request was required for a cache entry, and it failed with
193   // a non-offline error.
194   OFFLINE_STATUS_NETWORK_FAILED,
195
196   // A network request was required for a cache entry, it failed with an
197   // offline error, and we could serve stale data if
198   // LOAD_FROM_CACHE_IF_OFFLINE was set.
199   OFFLINE_STATUS_DATA_AVAILABLE_OFFLINE,
200
201   // A network request was required for a cache entry, it failed with
202   // an offline error, and there was no servable data in cache (even
203   // stale data).
204   OFFLINE_STATUS_DATA_UNAVAILABLE_OFFLINE,
205
206   OFFLINE_STATUS_MAX_ENTRIES
207 };
208
209 void RecordOfflineStatus(int load_flags, RequestOfflineStatus status) {
210   // Restrict to main frame to keep statistics close to
211   // "would have shown them something useful if offline mode was enabled".
212   if (load_flags & net::LOAD_MAIN_FRAME) {
213     UMA_HISTOGRAM_ENUMERATION("HttpCache.OfflineStatus", status,
214                               OFFLINE_STATUS_MAX_ENTRIES);
215   }
216 }
217
218 void RecordNoStoreHeaderHistogram(int load_flags,
219                                   const net::HttpResponseInfo* response) {
220   if (load_flags & net::LOAD_MAIN_FRAME) {
221     UMA_HISTOGRAM_BOOLEAN(
222         "Net.MainFrameNoStore",
223         response->headers->HasHeaderValue("cache-control", "no-store"));
224   }
225 }
226
227 base::Value* NetLogAsyncRevalidationInfoCallback(
228     const net::NetLog::Source& source,
229     const net::HttpRequestInfo* request,
230     net::NetLog::LogLevel log_level) {
231   base::DictionaryValue* dict = new base::DictionaryValue();
232   source.AddToEventParameters(dict);
233
234   dict->SetString("url", request->url.possibly_invalid_spec());
235   dict->SetString("method", request->method);
236   return dict;
237 }
238
239 enum ExternallyConditionalizedType {
240   EXTERNALLY_CONDITIONALIZED_CACHE_REQUIRES_VALIDATION,
241   EXTERNALLY_CONDITIONALIZED_CACHE_USABLE,
242   EXTERNALLY_CONDITIONALIZED_MISMATCHED_VALIDATORS,
243   EXTERNALLY_CONDITIONALIZED_MAX
244 };
245
246 }  // namespace
247
248 namespace net {
249
250 struct HeaderNameAndValue {
251   const char* name;
252   const char* value;
253 };
254
255 // If the request includes one of these request headers, then avoid caching
256 // to avoid getting confused.
257 static const HeaderNameAndValue kPassThroughHeaders[] = {
258   { "if-unmodified-since", NULL },  // causes unexpected 412s
259   { "if-match", NULL },             // causes unexpected 412s
260   { "if-range", NULL },
261   { NULL, NULL }
262 };
263
264 struct ValidationHeaderInfo {
265   const char* request_header_name;
266   const char* related_response_header_name;
267 };
268
269 static const ValidationHeaderInfo kValidationHeaders[] = {
270   { "if-modified-since", "last-modified" },
271   { "if-none-match", "etag" },
272 };
273
274 // If the request includes one of these request headers, then avoid reusing
275 // our cached copy if any.
276 static const HeaderNameAndValue kForceFetchHeaders[] = {
277   { "cache-control", "no-cache" },
278   { "pragma", "no-cache" },
279   { NULL, NULL }
280 };
281
282 // If the request includes one of these request headers, then force our
283 // cached copy (if any) to be revalidated before reusing it.
284 static const HeaderNameAndValue kForceValidateHeaders[] = {
285   { "cache-control", "max-age=0" },
286   { NULL, NULL }
287 };
288
289 static bool HeaderMatches(const HttpRequestHeaders& headers,
290                           const HeaderNameAndValue* search) {
291   for (; search->name; ++search) {
292     std::string header_value;
293     if (!headers.GetHeader(search->name, &header_value))
294       continue;
295
296     if (!search->value)
297       return true;
298
299     HttpUtil::ValuesIterator v(header_value.begin(), header_value.end(), ',');
300     while (v.GetNext()) {
301       if (LowerCaseEqualsASCII(v.value_begin(), v.value_end(), search->value))
302         return true;
303     }
304   }
305   return false;
306 }
307
308 //-----------------------------------------------------------------------------
309
310 HttpCache::Transaction::Transaction(
311     RequestPriority priority,
312     HttpCache* cache)
313     : next_state_(STATE_NONE),
314       request_(NULL),
315       priority_(priority),
316       cache_(cache->GetWeakPtr()),
317       entry_(NULL),
318       new_entry_(NULL),
319       new_response_(NULL),
320       mode_(NONE),
321       target_state_(STATE_NONE),
322       reading_(false),
323       invalid_range_(false),
324       truncated_(false),
325       is_sparse_(false),
326       range_requested_(false),
327       handling_206_(false),
328       cache_pending_(false),
329       done_reading_(false),
330       vary_mismatch_(false),
331       couldnt_conditionalize_request_(false),
332       bypass_lock_for_test_(false),
333       io_buf_len_(0),
334       read_offset_(0),
335       effective_load_flags_(0),
336       write_len_(0),
337       transaction_pattern_(PATTERN_UNDEFINED),
338       total_received_bytes_(0),
339       websocket_handshake_stream_base_create_helper_(NULL),
340       weak_factory_(this) {
341   COMPILE_ASSERT(HttpCache::Transaction::kNumValidationHeaders ==
342                  arraysize(kValidationHeaders),
343                  Invalid_number_of_validation_headers);
344
345   io_callback_ = base::Bind(&Transaction::OnIOComplete,
346                               weak_factory_.GetWeakPtr());
347 }
348
349 HttpCache::Transaction::~Transaction() {
350   // We may have to issue another IO, but we should never invoke the callback_
351   // after this point.
352   callback_.Reset();
353
354   if (cache_) {
355     if (entry_) {
356       bool cancel_request = reading_ && response_.headers.get();
357       if (cancel_request) {
358         if (partial_) {
359           entry_->disk_entry->CancelSparseIO();
360         } else {
361           cancel_request &= (response_.headers->response_code() == 200);
362         }
363       }
364
365       cache_->DoneWithEntry(entry_, this, cancel_request);
366     } else if (cache_pending_) {
367       cache_->RemovePendingTransaction(this);
368     }
369   }
370 }
371
372 int HttpCache::Transaction::WriteMetadata(IOBuffer* buf, int buf_len,
373                                           const CompletionCallback& callback) {
374   DCHECK(buf);
375   DCHECK_GT(buf_len, 0);
376   DCHECK(!callback.is_null());
377   if (!cache_.get() || !entry_)
378     return ERR_UNEXPECTED;
379
380   // We don't need to track this operation for anything.
381   // It could be possible to check if there is something already written and
382   // avoid writing again (it should be the same, right?), but let's allow the
383   // caller to "update" the contents with something new.
384   return entry_->disk_entry->WriteData(kMetadataIndex, 0, buf, buf_len,
385                                        callback, true);
386 }
387
388 bool HttpCache::Transaction::AddTruncatedFlag() {
389   DCHECK(mode_ & WRITE || mode_ == NONE);
390
391   // Don't set the flag for sparse entries.
392   if (partial_.get() && !truncated_)
393     return true;
394
395   if (!CanResume(true))
396     return false;
397
398   // We may have received the whole resource already.
399   if (done_reading_)
400     return true;
401
402   truncated_ = true;
403   target_state_ = STATE_NONE;
404   next_state_ = STATE_CACHE_WRITE_TRUNCATED_RESPONSE;
405   DoLoop(OK);
406   return true;
407 }
408
409 LoadState HttpCache::Transaction::GetWriterLoadState() const {
410   if (network_trans_.get())
411     return network_trans_->GetLoadState();
412   if (entry_ || !request_)
413     return LOAD_STATE_IDLE;
414   return LOAD_STATE_WAITING_FOR_CACHE;
415 }
416
417 const BoundNetLog& HttpCache::Transaction::net_log() const {
418   return net_log_;
419 }
420
421 int HttpCache::Transaction::Start(const HttpRequestInfo* request,
422                                   const CompletionCallback& callback,
423                                   const BoundNetLog& net_log) {
424   DCHECK(request);
425   DCHECK(!callback.is_null());
426
427   // Ensure that we only have one asynchronous call at a time.
428   DCHECK(callback_.is_null());
429   DCHECK(!reading_);
430   DCHECK(!network_trans_.get());
431   DCHECK(!entry_);
432
433   if (!cache_.get())
434     return ERR_UNEXPECTED;
435
436   SetRequest(net_log, request);
437
438   // We have to wait until the backend is initialized so we start the SM.
439   next_state_ = STATE_GET_BACKEND;
440   int rv = DoLoop(OK);
441
442   // Setting this here allows us to check for the existence of a callback_ to
443   // determine if we are still inside Start.
444   if (rv == ERR_IO_PENDING)
445     callback_ = callback;
446
447   return rv;
448 }
449
450 int HttpCache::Transaction::RestartIgnoringLastError(
451     const CompletionCallback& callback) {
452   DCHECK(!callback.is_null());
453
454   // Ensure that we only have one asynchronous call at a time.
455   DCHECK(callback_.is_null());
456
457   if (!cache_.get())
458     return ERR_UNEXPECTED;
459
460   int rv = RestartNetworkRequest();
461
462   if (rv == ERR_IO_PENDING)
463     callback_ = callback;
464
465   return rv;
466 }
467
468 int HttpCache::Transaction::RestartWithCertificate(
469     X509Certificate* client_cert,
470     const CompletionCallback& callback) {
471   DCHECK(!callback.is_null());
472
473   // Ensure that we only have one asynchronous call at a time.
474   DCHECK(callback_.is_null());
475
476   if (!cache_.get())
477     return ERR_UNEXPECTED;
478
479   int rv = RestartNetworkRequestWithCertificate(client_cert);
480
481   if (rv == ERR_IO_PENDING)
482     callback_ = callback;
483
484   return rv;
485 }
486
487 int HttpCache::Transaction::RestartWithAuth(
488     const AuthCredentials& credentials,
489     const CompletionCallback& callback) {
490   DCHECK(auth_response_.headers.get());
491   DCHECK(!callback.is_null());
492
493   // Ensure that we only have one asynchronous call at a time.
494   DCHECK(callback_.is_null());
495
496   if (!cache_.get())
497     return ERR_UNEXPECTED;
498
499   // Clear the intermediate response since we are going to start over.
500   auth_response_ = HttpResponseInfo();
501
502   int rv = RestartNetworkRequestWithAuth(credentials);
503
504   if (rv == ERR_IO_PENDING)
505     callback_ = callback;
506
507   return rv;
508 }
509
510 bool HttpCache::Transaction::IsReadyToRestartForAuth() {
511   if (!network_trans_.get())
512     return false;
513   return network_trans_->IsReadyToRestartForAuth();
514 }
515
516 int HttpCache::Transaction::Read(IOBuffer* buf, int buf_len,
517                                  const CompletionCallback& callback) {
518   DCHECK(buf);
519   DCHECK_GT(buf_len, 0);
520   DCHECK(!callback.is_null());
521
522   DCHECK(callback_.is_null());
523
524   if (!cache_.get())
525     return ERR_UNEXPECTED;
526
527   // If we have an intermediate auth response at this point, then it means the
528   // user wishes to read the network response (the error page).  If there is a
529   // previous response in the cache then we should leave it intact.
530   if (auth_response_.headers.get() && mode_ != NONE) {
531     UpdateTransactionPattern(PATTERN_NOT_COVERED);
532     DCHECK(mode_ & WRITE);
533     DoneWritingToEntry(mode_ == READ_WRITE);
534     mode_ = NONE;
535   }
536
537   reading_ = true;
538   int rv;
539
540   switch (mode_) {
541     case READ_WRITE:
542       DCHECK(partial_.get());
543       if (!network_trans_.get()) {
544         // We are just reading from the cache, but we may be writing later.
545         rv = ReadFromEntry(buf, buf_len);
546         break;
547       }
548     case NONE:
549     case WRITE:
550       DCHECK(network_trans_.get());
551       rv = ReadFromNetwork(buf, buf_len);
552       break;
553     case READ:
554       rv = ReadFromEntry(buf, buf_len);
555       break;
556     default:
557       NOTREACHED();
558       rv = ERR_FAILED;
559   }
560
561   if (rv == ERR_IO_PENDING) {
562     DCHECK(callback_.is_null());
563     callback_ = callback;
564   }
565   return rv;
566 }
567
568 void HttpCache::Transaction::StopCaching() {
569   // We really don't know where we are now. Hopefully there is no operation in
570   // progress, but nothing really prevents this method to be called after we
571   // returned ERR_IO_PENDING. We cannot attempt to truncate the entry at this
572   // point because we need the state machine for that (and even if we are really
573   // free, that would be an asynchronous operation). In other words, keep the
574   // entry how it is (it will be marked as truncated at destruction), and let
575   // the next piece of code that executes know that we are now reading directly
576   // from the net.
577   // TODO(mmenke):  This doesn't release the lock on the cache entry, so a
578   //                future request for the resource will be blocked on this one.
579   //                Fix this.
580   if (cache_.get() && entry_ && (mode_ & WRITE) && network_trans_.get() &&
581       !is_sparse_ && !range_requested_) {
582     mode_ = NONE;
583   }
584 }
585
586 bool HttpCache::Transaction::GetFullRequestHeaders(
587     HttpRequestHeaders* headers) const {
588   if (network_trans_)
589     return network_trans_->GetFullRequestHeaders(headers);
590
591   // TODO(ttuttle): Read headers from cache.
592   return false;
593 }
594
595 int64 HttpCache::Transaction::GetTotalReceivedBytes() const {
596   int64 total_received_bytes = total_received_bytes_;
597   if (network_trans_)
598     total_received_bytes += network_trans_->GetTotalReceivedBytes();
599   return total_received_bytes;
600 }
601
602 void HttpCache::Transaction::DoneReading() {
603   if (cache_.get() && entry_) {
604     DCHECK_NE(mode_, UPDATE);
605     if (mode_ & WRITE) {
606       DoneWritingToEntry(true);
607     } else if (mode_ & READ) {
608       // It is necessary to check mode_ & READ because it is possible
609       // for mode_ to be NONE and entry_ non-NULL with a write entry
610       // if StopCaching was called.
611       cache_->DoneReadingFromEntry(entry_, this);
612       entry_ = NULL;
613     }
614   }
615 }
616
617 const HttpResponseInfo* HttpCache::Transaction::GetResponseInfo() const {
618   // Null headers means we encountered an error or haven't a response yet
619   if (auth_response_.headers.get())
620     return &auth_response_;
621   return (response_.headers.get() || response_.ssl_info.cert.get() ||
622           response_.cert_request_info.get())
623              ? &response_
624              : NULL;
625 }
626
627 LoadState HttpCache::Transaction::GetLoadState() const {
628   LoadState state = GetWriterLoadState();
629   if (state != LOAD_STATE_WAITING_FOR_CACHE)
630     return state;
631
632   if (cache_.get())
633     return cache_->GetLoadStateForPendingTransaction(this);
634
635   return LOAD_STATE_IDLE;
636 }
637
638 UploadProgress HttpCache::Transaction::GetUploadProgress() const {
639   if (network_trans_.get())
640     return network_trans_->GetUploadProgress();
641   return final_upload_progress_;
642 }
643
644 void HttpCache::Transaction::SetQuicServerInfo(
645     QuicServerInfo* quic_server_info) {}
646
647 bool HttpCache::Transaction::GetLoadTimingInfo(
648     LoadTimingInfo* load_timing_info) const {
649   if (network_trans_)
650     return network_trans_->GetLoadTimingInfo(load_timing_info);
651
652   if (old_network_trans_load_timing_) {
653     *load_timing_info = *old_network_trans_load_timing_;
654     return true;
655   }
656
657   if (first_cache_access_since_.is_null())
658     return false;
659
660   // If the cache entry was opened, return that time.
661   load_timing_info->send_start = first_cache_access_since_;
662   // This time doesn't make much sense when reading from the cache, so just use
663   // the same time as send_start.
664   load_timing_info->send_end = first_cache_access_since_;
665   return true;
666 }
667
668 void HttpCache::Transaction::SetPriority(RequestPriority priority) {
669   priority_ = priority;
670   if (network_trans_)
671     network_trans_->SetPriority(priority_);
672 }
673
674 void HttpCache::Transaction::SetWebSocketHandshakeStreamCreateHelper(
675     WebSocketHandshakeStreamBase::CreateHelper* create_helper) {
676   websocket_handshake_stream_base_create_helper_ = create_helper;
677   if (network_trans_)
678     network_trans_->SetWebSocketHandshakeStreamCreateHelper(create_helper);
679 }
680
681 void HttpCache::Transaction::SetBeforeNetworkStartCallback(
682     const BeforeNetworkStartCallback& callback) {
683   DCHECK(!network_trans_);
684   before_network_start_callback_ = callback;
685 }
686
687 void HttpCache::Transaction::SetBeforeProxyHeadersSentCallback(
688     const BeforeProxyHeadersSentCallback& callback) {
689   DCHECK(!network_trans_);
690   before_proxy_headers_sent_callback_ = callback;
691 }
692
693 int HttpCache::Transaction::ResumeNetworkStart() {
694   if (network_trans_)
695     return network_trans_->ResumeNetworkStart();
696   return ERR_UNEXPECTED;
697 }
698
699 //-----------------------------------------------------------------------------
700
701 void HttpCache::Transaction::DoCallback(int rv) {
702   DCHECK(rv != ERR_IO_PENDING);
703   DCHECK(!callback_.is_null());
704
705   read_buf_ = NULL;  // Release the buffer before invoking the callback.
706
707   // Since Run may result in Read being called, clear callback_ up front.
708   CompletionCallback c = callback_;
709   callback_.Reset();
710   c.Run(rv);
711 }
712
713 int HttpCache::Transaction::HandleResult(int rv) {
714   DCHECK(rv != ERR_IO_PENDING);
715   if (!callback_.is_null())
716     DoCallback(rv);
717
718   return rv;
719 }
720
721 // A few common patterns: (Foo* means Foo -> FooComplete)
722 //
723 // 1. Not-cached entry:
724 //   Start():
725 //   GetBackend* -> InitEntry -> OpenEntry* -> CreateEntry* -> AddToEntry* ->
726 //   SendRequest* -> SuccessfulSendRequest -> OverwriteCachedResponse ->
727 //   CacheWriteResponse* -> TruncateCachedData* -> TruncateCachedMetadata* ->
728 //   PartialHeadersReceived
729 //
730 //   Read():
731 //   NetworkRead* -> CacheWriteData*
732 //
733 // 2. Cached entry, no validation:
734 //   Start():
735 //   GetBackend* -> InitEntry -> OpenEntry* -> AddToEntry* -> CacheReadResponse*
736 //   -> BeginPartialCacheValidation() -> BeginCacheValidation() ->
737 //   SetupEntryForRead()
738 //
739 //   Read():
740 //   CacheReadData*
741 //
742 // 3. Cached entry, validation (304):
743 //   Start():
744 //   GetBackend* -> InitEntry -> OpenEntry* -> AddToEntry* -> CacheReadResponse*
745 //   -> BeginPartialCacheValidation() -> BeginCacheValidation() ->
746 //   SendRequest* -> SuccessfulSendRequest -> UpdateCachedResponse ->
747 //   CacheWriteResponse* -> UpdateCachedResponseComplete ->
748 //   OverwriteCachedResponse -> PartialHeadersReceived
749 //
750 //   Read():
751 //   CacheReadData*
752 //
753 // 4. Cached entry, validation and replace (200):
754 //   Start():
755 //   GetBackend* -> InitEntry -> OpenEntry* -> AddToEntry* -> CacheReadResponse*
756 //   -> BeginPartialCacheValidation() -> BeginCacheValidation() ->
757 //   SendRequest* -> SuccessfulSendRequest -> OverwriteCachedResponse ->
758 //   CacheWriteResponse* -> DoTruncateCachedData* -> TruncateCachedMetadata* ->
759 //   PartialHeadersReceived
760 //
761 //   Read():
762 //   NetworkRead* -> CacheWriteData*
763 //
764 // 5. Sparse entry, partially cached, byte range request:
765 //   Start():
766 //   GetBackend* -> InitEntry -> OpenEntry* -> AddToEntry* -> CacheReadResponse*
767 //   -> BeginPartialCacheValidation() -> CacheQueryData* ->
768 //   ValidateEntryHeadersAndContinue() -> StartPartialCacheValidation ->
769 //   CompletePartialCacheValidation -> BeginCacheValidation() -> SendRequest* ->
770 //   SuccessfulSendRequest -> UpdateCachedResponse -> CacheWriteResponse* ->
771 //   UpdateCachedResponseComplete -> OverwriteCachedResponse ->
772 //   PartialHeadersReceived
773 //
774 //   Read() 1:
775 //   NetworkRead* -> CacheWriteData*
776 //
777 //   Read() 2:
778 //   NetworkRead* -> CacheWriteData* -> StartPartialCacheValidation ->
779 //   CompletePartialCacheValidation -> CacheReadData* ->
780 //
781 //   Read() 3:
782 //   CacheReadData* -> StartPartialCacheValidation ->
783 //   CompletePartialCacheValidation -> BeginCacheValidation() -> SendRequest* ->
784 //   SuccessfulSendRequest -> UpdateCachedResponse* -> OverwriteCachedResponse
785 //   -> PartialHeadersReceived -> NetworkRead* -> CacheWriteData*
786 //
787 // 6. HEAD. Not-cached entry:
788 //   Pass through. Don't save a HEAD by itself.
789 //   Start():
790 //   GetBackend* -> InitEntry -> OpenEntry* -> SendRequest*
791 //
792 // 7. HEAD. Cached entry, no validation:
793 //   Start():
794 //   The same flow as for a GET request (example #2)
795 //
796 //   Read():
797 //   CacheReadData (returns 0)
798 //
799 // 8. HEAD. Cached entry, validation (304):
800 //   The request updates the stored headers.
801 //   Start(): Same as for a GET request (example #3)
802 //
803 //   Read():
804 //   CacheReadData (returns 0)
805 //
806 // 9. HEAD. Cached entry, validation and replace (200):
807 //   Pass through. The request dooms the old entry, as a HEAD won't be stored by
808 //   itself.
809 //   Start():
810 //   GetBackend* -> InitEntry -> OpenEntry* -> AddToEntry* -> CacheReadResponse*
811 //   -> BeginPartialCacheValidation() -> BeginCacheValidation() ->
812 //   SendRequest* -> SuccessfulSendRequest -> OverwriteCachedResponse
813 //
814 // 10. HEAD. Sparse entry, partially cached:
815 //   Serve the request from the cache, as long as it doesn't require
816 //   revalidation. Ignore missing ranges when deciding to revalidate. If the
817 //   entry requires revalidation, ignore the whole request and go to full pass
818 //   through (the result of the HEAD request will NOT update the entry).
819 //
820 //   Start(): Basically the same as example 7, as we never create a partial_
821 //   object for this request.
822 //
823 int HttpCache::Transaction::DoLoop(int result) {
824   DCHECK(next_state_ != STATE_NONE);
825
826   int rv = result;
827   do {
828     State state = next_state_;
829     next_state_ = STATE_NONE;
830     switch (state) {
831       case STATE_GET_BACKEND:
832         DCHECK_EQ(OK, rv);
833         rv = DoGetBackend();
834         break;
835       case STATE_GET_BACKEND_COMPLETE:
836         rv = DoGetBackendComplete(rv);
837         break;
838       case STATE_SEND_REQUEST:
839         DCHECK_EQ(OK, rv);
840         rv = DoSendRequest();
841         break;
842       case STATE_SEND_REQUEST_COMPLETE:
843         rv = DoSendRequestComplete(rv);
844         break;
845       case STATE_SUCCESSFUL_SEND_REQUEST:
846         DCHECK_EQ(OK, rv);
847         rv = DoSuccessfulSendRequest();
848         break;
849       case STATE_NETWORK_READ:
850         DCHECK_EQ(OK, rv);
851         rv = DoNetworkRead();
852         break;
853       case STATE_NETWORK_READ_COMPLETE:
854         rv = DoNetworkReadComplete(rv);
855         break;
856       case STATE_INIT_ENTRY:
857         DCHECK_EQ(OK, rv);
858         rv = DoInitEntry();
859         break;
860       case STATE_OPEN_ENTRY:
861         DCHECK_EQ(OK, rv);
862         rv = DoOpenEntry();
863         break;
864       case STATE_OPEN_ENTRY_COMPLETE:
865         rv = DoOpenEntryComplete(rv);
866         break;
867       case STATE_CREATE_ENTRY:
868         DCHECK_EQ(OK, rv);
869         rv = DoCreateEntry();
870         break;
871       case STATE_CREATE_ENTRY_COMPLETE:
872         rv = DoCreateEntryComplete(rv);
873         break;
874       case STATE_DOOM_ENTRY:
875         DCHECK_EQ(OK, rv);
876         rv = DoDoomEntry();
877         break;
878       case STATE_DOOM_ENTRY_COMPLETE:
879         rv = DoDoomEntryComplete(rv);
880         break;
881       case STATE_ADD_TO_ENTRY:
882         DCHECK_EQ(OK, rv);
883         rv = DoAddToEntry();
884         break;
885       case STATE_ADD_TO_ENTRY_COMPLETE:
886         rv = DoAddToEntryComplete(rv);
887         break;
888       case STATE_START_PARTIAL_CACHE_VALIDATION:
889         DCHECK_EQ(OK, rv);
890         rv = DoStartPartialCacheValidation();
891         break;
892       case STATE_COMPLETE_PARTIAL_CACHE_VALIDATION:
893         rv = DoCompletePartialCacheValidation(rv);
894         break;
895       case STATE_UPDATE_CACHED_RESPONSE:
896         DCHECK_EQ(OK, rv);
897         rv = DoUpdateCachedResponse();
898         break;
899       case STATE_UPDATE_CACHED_RESPONSE_COMPLETE:
900         rv = DoUpdateCachedResponseComplete(rv);
901         break;
902       case STATE_OVERWRITE_CACHED_RESPONSE:
903         DCHECK_EQ(OK, rv);
904         rv = DoOverwriteCachedResponse();
905         break;
906       case STATE_TRUNCATE_CACHED_DATA:
907         DCHECK_EQ(OK, rv);
908         rv = DoTruncateCachedData();
909         break;
910       case STATE_TRUNCATE_CACHED_DATA_COMPLETE:
911         rv = DoTruncateCachedDataComplete(rv);
912         break;
913       case STATE_TRUNCATE_CACHED_METADATA:
914         DCHECK_EQ(OK, rv);
915         rv = DoTruncateCachedMetadata();
916         break;
917       case STATE_TRUNCATE_CACHED_METADATA_COMPLETE:
918         rv = DoTruncateCachedMetadataComplete(rv);
919         break;
920       case STATE_PARTIAL_HEADERS_RECEIVED:
921         DCHECK_EQ(OK, rv);
922         rv = DoPartialHeadersReceived();
923         break;
924       case STATE_CACHE_READ_RESPONSE:
925         DCHECK_EQ(OK, rv);
926         rv = DoCacheReadResponse();
927         break;
928       case STATE_CACHE_READ_RESPONSE_COMPLETE:
929         rv = DoCacheReadResponseComplete(rv);
930         break;
931       case STATE_CACHE_WRITE_RESPONSE:
932         DCHECK_EQ(OK, rv);
933         rv = DoCacheWriteResponse();
934         break;
935       case STATE_CACHE_WRITE_TRUNCATED_RESPONSE:
936         DCHECK_EQ(OK, rv);
937         rv = DoCacheWriteTruncatedResponse();
938         break;
939       case STATE_CACHE_WRITE_RESPONSE_COMPLETE:
940         rv = DoCacheWriteResponseComplete(rv);
941         break;
942       case STATE_CACHE_READ_METADATA:
943         DCHECK_EQ(OK, rv);
944         rv = DoCacheReadMetadata();
945         break;
946       case STATE_CACHE_READ_METADATA_COMPLETE:
947         rv = DoCacheReadMetadataComplete(rv);
948         break;
949       case STATE_CACHE_QUERY_DATA:
950         DCHECK_EQ(OK, rv);
951         rv = DoCacheQueryData();
952         break;
953       case STATE_CACHE_QUERY_DATA_COMPLETE:
954         rv = DoCacheQueryDataComplete(rv);
955         break;
956       case STATE_CACHE_READ_DATA:
957         DCHECK_EQ(OK, rv);
958         rv = DoCacheReadData();
959         break;
960       case STATE_CACHE_READ_DATA_COMPLETE:
961         rv = DoCacheReadDataComplete(rv);
962         break;
963       case STATE_CACHE_WRITE_DATA:
964         rv = DoCacheWriteData(rv);
965         break;
966       case STATE_CACHE_WRITE_DATA_COMPLETE:
967         rv = DoCacheWriteDataComplete(rv);
968         break;
969       default:
970         NOTREACHED() << "bad state";
971         rv = ERR_FAILED;
972         break;
973     }
974   } while (rv != ERR_IO_PENDING && next_state_ != STATE_NONE);
975
976   if (rv != ERR_IO_PENDING)
977     HandleResult(rv);
978
979   return rv;
980 }
981
982 int HttpCache::Transaction::DoGetBackend() {
983   cache_pending_ = true;
984   next_state_ = STATE_GET_BACKEND_COMPLETE;
985   net_log_.BeginEvent(NetLog::TYPE_HTTP_CACHE_GET_BACKEND);
986   return cache_->GetBackendForTransaction(this);
987 }
988
989 int HttpCache::Transaction::DoGetBackendComplete(int result) {
990   DCHECK(result == OK || result == ERR_FAILED);
991   net_log_.EndEventWithNetErrorCode(NetLog::TYPE_HTTP_CACHE_GET_BACKEND,
992                                     result);
993   cache_pending_ = false;
994
995   if (!ShouldPassThrough()) {
996     cache_key_ = cache_->GenerateCacheKey(request_);
997
998     // Requested cache access mode.
999     if (effective_load_flags_ & LOAD_ONLY_FROM_CACHE) {
1000       mode_ = READ;
1001     } else if (effective_load_flags_ & LOAD_BYPASS_CACHE) {
1002       mode_ = WRITE;
1003     } else {
1004       mode_ = READ_WRITE;
1005     }
1006
1007     // Downgrade to UPDATE if the request has been externally conditionalized.
1008     if (external_validation_.initialized) {
1009       if (mode_ & WRITE) {
1010         // Strip off the READ_DATA bit (and maybe add back a READ_META bit
1011         // in case READ was off).
1012         mode_ = UPDATE;
1013       } else {
1014         mode_ = NONE;
1015       }
1016     }
1017   }
1018
1019   // Use PUT and DELETE only to invalidate existing stored entries.
1020   if ((request_->method == "PUT" || request_->method == "DELETE") &&
1021       mode_ != READ_WRITE && mode_ != WRITE) {
1022     mode_ = NONE;
1023   }
1024
1025   // Note that if mode_ == UPDATE (which is tied to external_validation_), the
1026   // transaction behaves the same for GET and HEAD requests at this point: if it
1027   // was not modified, the entry is updated and a response is not returned from
1028   // the cache. If we receive 200, it doesn't matter if there was a validation
1029   // header or not.
1030   if (request_->method == "HEAD" && mode_ == WRITE)
1031     mode_ = NONE;
1032
1033   // If must use cache, then we must fail.  This can happen for back/forward
1034   // navigations to a page generated via a form post.
1035   if (!(mode_ & READ) && effective_load_flags_ & LOAD_ONLY_FROM_CACHE)
1036     return ERR_CACHE_MISS;
1037
1038   if (mode_ == NONE) {
1039     if (partial_.get()) {
1040       partial_->RestoreHeaders(&custom_request_->extra_headers);
1041       partial_.reset();
1042     }
1043     next_state_ = STATE_SEND_REQUEST;
1044   } else {
1045     next_state_ = STATE_INIT_ENTRY;
1046   }
1047
1048   // This is only set if we have something to do with the response.
1049   range_requested_ = (partial_.get() != NULL);
1050
1051   return OK;
1052 }
1053
1054 int HttpCache::Transaction::DoSendRequest() {
1055   DCHECK(mode_ & WRITE || mode_ == NONE);
1056   DCHECK(!network_trans_.get());
1057
1058   send_request_since_ = TimeTicks::Now();
1059
1060   // Create a network transaction.
1061   int rv = cache_->network_layer_->CreateTransaction(priority_,
1062                                                      &network_trans_);
1063   if (rv != OK)
1064     return rv;
1065   network_trans_->SetBeforeNetworkStartCallback(before_network_start_callback_);
1066   network_trans_->SetBeforeProxyHeadersSentCallback(
1067       before_proxy_headers_sent_callback_);
1068
1069   // Old load timing information, if any, is now obsolete.
1070   old_network_trans_load_timing_.reset();
1071
1072   if (websocket_handshake_stream_base_create_helper_)
1073     network_trans_->SetWebSocketHandshakeStreamCreateHelper(
1074         websocket_handshake_stream_base_create_helper_);
1075
1076   next_state_ = STATE_SEND_REQUEST_COMPLETE;
1077   rv = network_trans_->Start(request_, io_callback_, net_log_);
1078   return rv;
1079 }
1080
1081 int HttpCache::Transaction::DoSendRequestComplete(int result) {
1082   if (!cache_.get())
1083     return ERR_UNEXPECTED;
1084
1085   // If requested, and we have a readable cache entry, and we have
1086   // an error indicating that we're offline as opposed to in contact
1087   // with a bad server, read from cache anyway.
1088   if (IsOfflineError(result)) {
1089     if (mode_ == READ_WRITE && entry_ && !partial_) {
1090       RecordOfflineStatus(effective_load_flags_,
1091                           OFFLINE_STATUS_DATA_AVAILABLE_OFFLINE);
1092       if (effective_load_flags_ & LOAD_FROM_CACHE_IF_OFFLINE) {
1093         UpdateTransactionPattern(PATTERN_NOT_COVERED);
1094         response_.server_data_unavailable = true;
1095         return SetupEntryForRead();
1096       }
1097     } else {
1098       RecordOfflineStatus(effective_load_flags_,
1099                           OFFLINE_STATUS_DATA_UNAVAILABLE_OFFLINE);
1100     }
1101   } else {
1102     RecordOfflineStatus(effective_load_flags_,
1103                         (result == OK ? OFFLINE_STATUS_NETWORK_SUCCEEDED :
1104                                         OFFLINE_STATUS_NETWORK_FAILED));
1105   }
1106
1107   // If we tried to conditionalize the request and failed, we know
1108   // we won't be reading from the cache after this point.
1109   if (couldnt_conditionalize_request_)
1110     mode_ = WRITE;
1111
1112   if (result == OK) {
1113     next_state_ = STATE_SUCCESSFUL_SEND_REQUEST;
1114     return OK;
1115   }
1116
1117   // Do not record requests that have network errors or restarts.
1118   UpdateTransactionPattern(PATTERN_NOT_COVERED);
1119   if (IsCertificateError(result)) {
1120     const HttpResponseInfo* response = network_trans_->GetResponseInfo();
1121     // If we get a certificate error, then there is a certificate in ssl_info,
1122     // so GetResponseInfo() should never return NULL here.
1123     DCHECK(response);
1124     response_.ssl_info = response->ssl_info;
1125   } else if (result == ERR_SSL_CLIENT_AUTH_CERT_NEEDED) {
1126     const HttpResponseInfo* response = network_trans_->GetResponseInfo();
1127     DCHECK(response);
1128     response_.cert_request_info = response->cert_request_info;
1129   } else if (response_.was_cached) {
1130     DoneWritingToEntry(true);
1131   }
1132   return result;
1133 }
1134
1135 // We received the response headers and there is no error.
1136 int HttpCache::Transaction::DoSuccessfulSendRequest() {
1137   DCHECK(!new_response_);
1138   const HttpResponseInfo* new_response = network_trans_->GetResponseInfo();
1139   bool authentication_failure = false;
1140
1141   if (new_response->headers->response_code() == 401 ||
1142       new_response->headers->response_code() == 407) {
1143     auth_response_ = *new_response;
1144     if (!reading_)
1145       return OK;
1146
1147     // We initiated a second request the caller doesn't know about. We should be
1148     // able to authenticate this request because we should have authenticated
1149     // this URL moments ago.
1150     if (IsReadyToRestartForAuth()) {
1151       DCHECK(!response_.auth_challenge.get());
1152       next_state_ = STATE_SEND_REQUEST_COMPLETE;
1153       // In theory we should check to see if there are new cookies, but there
1154       // is no way to do that from here.
1155       return network_trans_->RestartWithAuth(AuthCredentials(), io_callback_);
1156     }
1157
1158     // We have to perform cleanup at this point so that at least the next
1159     // request can succeed.
1160     authentication_failure = true;
1161     if (entry_)
1162       DoomPartialEntry(false);
1163     mode_ = NONE;
1164     partial_.reset();
1165   }
1166
1167   new_response_ = new_response;
1168   if (authentication_failure ||
1169       (!ValidatePartialResponse() && !auth_response_.headers.get())) {
1170     // Something went wrong with this request and we have to restart it.
1171     // If we have an authentication response, we are exposed to weird things
1172     // hapenning if the user cancels the authentication before we receive
1173     // the new response.
1174     UpdateTransactionPattern(PATTERN_NOT_COVERED);
1175     response_ = HttpResponseInfo();
1176     ResetNetworkTransaction();
1177     new_response_ = NULL;
1178     next_state_ = STATE_SEND_REQUEST;
1179     return OK;
1180   }
1181
1182   if (handling_206_ && mode_ == READ_WRITE && !truncated_ && !is_sparse_) {
1183     // We have stored the full entry, but it changed and the server is
1184     // sending a range. We have to delete the old entry.
1185     UpdateTransactionPattern(PATTERN_NOT_COVERED);
1186     DoneWritingToEntry(false);
1187   }
1188
1189   if (mode_ == WRITE &&
1190       transaction_pattern_ != PATTERN_ENTRY_CANT_CONDITIONALIZE) {
1191     UpdateTransactionPattern(PATTERN_ENTRY_NOT_CACHED);
1192   }
1193
1194   // Invalidate any cached GET with a successful PUT or DELETE.
1195   if (mode_ == WRITE &&
1196       (request_->method == "PUT" || request_->method == "DELETE")) {
1197     if (NonErrorResponse(new_response->headers->response_code())) {
1198       int ret = cache_->DoomEntry(cache_key_, NULL);
1199       DCHECK_EQ(OK, ret);
1200     }
1201     cache_->DoneWritingToEntry(entry_, true);
1202     entry_ = NULL;
1203     mode_ = NONE;
1204   }
1205
1206   // Invalidate any cached GET with a successful POST.
1207   if (!(effective_load_flags_ & LOAD_DISABLE_CACHE) &&
1208       request_->method == "POST" &&
1209       NonErrorResponse(new_response->headers->response_code())) {
1210     cache_->DoomMainEntryForUrl(request_->url);
1211   }
1212
1213   RecordNoStoreHeaderHistogram(request_->load_flags, new_response);
1214
1215   if (new_response_->headers->response_code() == 416 &&
1216       (request_->method == "GET" || request_->method == "POST")) {
1217     // If there is an active entry it may be destroyed with this transaction.
1218     response_ = *new_response_;
1219     return OK;
1220   }
1221
1222   // Are we expecting a response to a conditional query?
1223   if (mode_ == READ_WRITE || mode_ == UPDATE) {
1224     if (new_response->headers->response_code() == 304 || handling_206_) {
1225       UpdateTransactionPattern(PATTERN_ENTRY_VALIDATED);
1226       next_state_ = STATE_UPDATE_CACHED_RESPONSE;
1227       return OK;
1228     }
1229     UpdateTransactionPattern(PATTERN_ENTRY_UPDATED);
1230     mode_ = WRITE;
1231   }
1232
1233   next_state_ = STATE_OVERWRITE_CACHED_RESPONSE;
1234   return OK;
1235 }
1236
1237 int HttpCache::Transaction::DoNetworkRead() {
1238   next_state_ = STATE_NETWORK_READ_COMPLETE;
1239   return network_trans_->Read(read_buf_.get(), io_buf_len_, io_callback_);
1240 }
1241
1242 int HttpCache::Transaction::DoNetworkReadComplete(int result) {
1243   DCHECK(mode_ & WRITE || mode_ == NONE);
1244
1245   if (!cache_.get())
1246     return ERR_UNEXPECTED;
1247
1248   // If there is an error or we aren't saving the data, we are done; just wait
1249   // until the destructor runs to see if we can keep the data.
1250   if (mode_ == NONE || result < 0)
1251     return result;
1252
1253   next_state_ = STATE_CACHE_WRITE_DATA;
1254   return result;
1255 }
1256
1257 int HttpCache::Transaction::DoInitEntry() {
1258   DCHECK(!new_entry_);
1259
1260   if (!cache_.get())
1261     return ERR_UNEXPECTED;
1262
1263   if (mode_ == WRITE) {
1264     next_state_ = STATE_DOOM_ENTRY;
1265     return OK;
1266   }
1267
1268   next_state_ = STATE_OPEN_ENTRY;
1269   return OK;
1270 }
1271
1272 int HttpCache::Transaction::DoOpenEntry() {
1273   DCHECK(!new_entry_);
1274   next_state_ = STATE_OPEN_ENTRY_COMPLETE;
1275   cache_pending_ = true;
1276   net_log_.BeginEvent(NetLog::TYPE_HTTP_CACHE_OPEN_ENTRY);
1277   first_cache_access_since_ = TimeTicks::Now();
1278   return cache_->OpenEntry(cache_key_, &new_entry_, this);
1279 }
1280
1281 int HttpCache::Transaction::DoOpenEntryComplete(int result) {
1282   // It is important that we go to STATE_ADD_TO_ENTRY whenever the result is
1283   // OK, otherwise the cache will end up with an active entry without any
1284   // transaction attached.
1285   net_log_.EndEventWithNetErrorCode(NetLog::TYPE_HTTP_CACHE_OPEN_ENTRY, result);
1286   cache_pending_ = false;
1287   if (result == OK) {
1288     next_state_ = STATE_ADD_TO_ENTRY;
1289     return OK;
1290   }
1291
1292   if (result == ERR_CACHE_RACE) {
1293     next_state_ = STATE_INIT_ENTRY;
1294     return OK;
1295   }
1296
1297   if (request_->method == "PUT" || request_->method == "DELETE" ||
1298       (request_->method == "HEAD" && mode_ == READ_WRITE)) {
1299     DCHECK(mode_ == READ_WRITE || mode_ == WRITE || request_->method == "HEAD");
1300     mode_ = NONE;
1301     next_state_ = STATE_SEND_REQUEST;
1302     return OK;
1303   }
1304
1305   if (mode_ == READ_WRITE) {
1306     mode_ = WRITE;
1307     next_state_ = STATE_CREATE_ENTRY;
1308     return OK;
1309   }
1310   if (mode_ == UPDATE) {
1311     // There is no cache entry to update; proceed without caching.
1312     mode_ = NONE;
1313     next_state_ = STATE_SEND_REQUEST;
1314     return OK;
1315   }
1316   if (cache_->mode() == PLAYBACK)
1317     DVLOG(1) << "Playback Cache Miss: " << request_->url;
1318
1319   // The entry does not exist, and we are not permitted to create a new entry,
1320   // so we must fail.
1321   return ERR_CACHE_MISS;
1322 }
1323
1324 int HttpCache::Transaction::DoCreateEntry() {
1325   DCHECK(!new_entry_);
1326   next_state_ = STATE_CREATE_ENTRY_COMPLETE;
1327   cache_pending_ = true;
1328   net_log_.BeginEvent(NetLog::TYPE_HTTP_CACHE_CREATE_ENTRY);
1329   return cache_->CreateEntry(cache_key_, &new_entry_, this);
1330 }
1331
1332 int HttpCache::Transaction::DoCreateEntryComplete(int result) {
1333   // It is important that we go to STATE_ADD_TO_ENTRY whenever the result is
1334   // OK, otherwise the cache will end up with an active entry without any
1335   // transaction attached.
1336   net_log_.EndEventWithNetErrorCode(NetLog::TYPE_HTTP_CACHE_CREATE_ENTRY,
1337                                     result);
1338   cache_pending_ = false;
1339   next_state_ = STATE_ADD_TO_ENTRY;
1340
1341   if (result == ERR_CACHE_RACE) {
1342     next_state_ = STATE_INIT_ENTRY;
1343     return OK;
1344   }
1345
1346   if (result != OK) {
1347     // We have a race here: Maybe we failed to open the entry and decided to
1348     // create one, but by the time we called create, another transaction already
1349     // created the entry. If we want to eliminate this issue, we need an atomic
1350     // OpenOrCreate() method exposed by the disk cache.
1351     DLOG(WARNING) << "Unable to create cache entry";
1352     mode_ = NONE;
1353     if (partial_.get())
1354       partial_->RestoreHeaders(&custom_request_->extra_headers);
1355     next_state_ = STATE_SEND_REQUEST;
1356   }
1357   return OK;
1358 }
1359
1360 int HttpCache::Transaction::DoDoomEntry() {
1361   next_state_ = STATE_DOOM_ENTRY_COMPLETE;
1362   cache_pending_ = true;
1363   if (first_cache_access_since_.is_null())
1364     first_cache_access_since_ = TimeTicks::Now();
1365   net_log_.BeginEvent(NetLog::TYPE_HTTP_CACHE_DOOM_ENTRY);
1366   return cache_->DoomEntry(cache_key_, this);
1367 }
1368
1369 int HttpCache::Transaction::DoDoomEntryComplete(int result) {
1370   net_log_.EndEventWithNetErrorCode(NetLog::TYPE_HTTP_CACHE_DOOM_ENTRY, result);
1371   next_state_ = STATE_CREATE_ENTRY;
1372   cache_pending_ = false;
1373   if (result == ERR_CACHE_RACE)
1374     next_state_ = STATE_INIT_ENTRY;
1375   return OK;
1376 }
1377
1378 int HttpCache::Transaction::DoAddToEntry() {
1379   DCHECK(new_entry_);
1380   cache_pending_ = true;
1381   next_state_ = STATE_ADD_TO_ENTRY_COMPLETE;
1382   net_log_.BeginEvent(NetLog::TYPE_HTTP_CACHE_ADD_TO_ENTRY);
1383   DCHECK(entry_lock_waiting_since_.is_null());
1384   entry_lock_waiting_since_ = TimeTicks::Now();
1385   int rv = cache_->AddTransactionToEntry(new_entry_, this);
1386   if (rv == ERR_IO_PENDING) {
1387     if (bypass_lock_for_test_) {
1388       OnAddToEntryTimeout(entry_lock_waiting_since_);
1389     } else {
1390       int timeout_milliseconds = 20 * 1000;
1391       if (partial_ && new_entry_->writer &&
1392           new_entry_->writer->range_requested_) {
1393         // Quickly timeout and bypass the cache if we're a range request and
1394         // we're blocked by the reader/writer lock. Doing so eliminates a long
1395         // running issue, http://crbug.com/31014, where two of the same media
1396         // resources could not be played back simultaneously due to one locking
1397         // the cache entry until the entire video was downloaded.
1398         //
1399         // Bypassing the cache is not ideal, as we are now ignoring the cache
1400         // entirely for all range requests to a resource beyond the first. This
1401         // is however a much more succinct solution than the alternatives, which
1402         // would require somewhat significant changes to the http caching logic.
1403         //
1404         // Allow some timeout slack for the entry addition to complete in case
1405         // the writer lock is imminently released; we want to avoid skipping
1406         // the cache if at all possible. See http://crbug.com/408765
1407         timeout_milliseconds = 25;
1408       }
1409       base::MessageLoop::current()->PostDelayedTask(
1410           FROM_HERE,
1411           base::Bind(&HttpCache::Transaction::OnAddToEntryTimeout,
1412                      weak_factory_.GetWeakPtr(), entry_lock_waiting_since_),
1413           TimeDelta::FromMilliseconds(timeout_milliseconds));
1414     }
1415   }
1416   return rv;
1417 }
1418
1419 int HttpCache::Transaction::DoAddToEntryComplete(int result) {
1420   net_log_.EndEventWithNetErrorCode(NetLog::TYPE_HTTP_CACHE_ADD_TO_ENTRY,
1421                                     result);
1422   const TimeDelta entry_lock_wait =
1423       TimeTicks::Now() - entry_lock_waiting_since_;
1424   UMA_HISTOGRAM_TIMES("HttpCache.EntryLockWait", entry_lock_wait);
1425
1426   entry_lock_waiting_since_ = TimeTicks();
1427   DCHECK(new_entry_);
1428   cache_pending_ = false;
1429
1430   if (result == OK)
1431     entry_ = new_entry_;
1432
1433   // If there is a failure, the cache should have taken care of new_entry_.
1434   new_entry_ = NULL;
1435
1436   if (result == ERR_CACHE_RACE) {
1437     next_state_ = STATE_INIT_ENTRY;
1438     return OK;
1439   }
1440
1441   if (result == ERR_CACHE_LOCK_TIMEOUT) {
1442     // The cache is busy, bypass it for this transaction.
1443     mode_ = NONE;
1444     next_state_ = STATE_SEND_REQUEST;
1445     if (partial_) {
1446       partial_->RestoreHeaders(&custom_request_->extra_headers);
1447       partial_.reset();
1448     }
1449     return OK;
1450   }
1451
1452   if (result != OK) {
1453     NOTREACHED();
1454     return result;
1455   }
1456
1457   if (mode_ == WRITE) {
1458     if (partial_.get())
1459       partial_->RestoreHeaders(&custom_request_->extra_headers);
1460     next_state_ = STATE_SEND_REQUEST;
1461   } else {
1462     // We have to read the headers from the cached entry.
1463     DCHECK(mode_ & READ_META);
1464     next_state_ = STATE_CACHE_READ_RESPONSE;
1465   }
1466   return OK;
1467 }
1468
1469 // We may end up here multiple times for a given request.
1470 int HttpCache::Transaction::DoStartPartialCacheValidation() {
1471   if (mode_ == NONE)
1472     return OK;
1473
1474   next_state_ = STATE_COMPLETE_PARTIAL_CACHE_VALIDATION;
1475   return partial_->ShouldValidateCache(entry_->disk_entry, io_callback_);
1476 }
1477
1478 int HttpCache::Transaction::DoCompletePartialCacheValidation(int result) {
1479   if (!result) {
1480     // This is the end of the request.
1481     if (mode_ & WRITE) {
1482       DoneWritingToEntry(true);
1483     } else {
1484       cache_->DoneReadingFromEntry(entry_, this);
1485       entry_ = NULL;
1486     }
1487     return result;
1488   }
1489
1490   if (result < 0)
1491     return result;
1492
1493   partial_->PrepareCacheValidation(entry_->disk_entry,
1494                                    &custom_request_->extra_headers);
1495
1496   if (reading_ && partial_->IsCurrentRangeCached()) {
1497     next_state_ = STATE_CACHE_READ_DATA;
1498     return OK;
1499   }
1500
1501   return BeginCacheValidation();
1502 }
1503
1504 // We received 304 or 206 and we want to update the cached response headers.
1505 int HttpCache::Transaction::DoUpdateCachedResponse() {
1506   next_state_ = STATE_UPDATE_CACHED_RESPONSE_COMPLETE;
1507   int rv = OK;
1508   // Update cached response based on headers in new_response.
1509   // TODO(wtc): should we update cached certificate (response_.ssl_info), too?
1510   response_.headers->Update(*new_response_->headers.get());
1511   response_.response_time = new_response_->response_time;
1512   response_.request_time = new_response_->request_time;
1513   response_.network_accessed = new_response_->network_accessed;
1514
1515   if (response_.headers->HasHeaderValue("cache-control", "no-store")) {
1516     if (!entry_->doomed) {
1517       int ret = cache_->DoomEntry(cache_key_, NULL);
1518       DCHECK_EQ(OK, ret);
1519     }
1520   } else {
1521     // If we are already reading, we already updated the headers for this
1522     // request; doing it again will change Content-Length.
1523     if (!reading_) {
1524       target_state_ = STATE_UPDATE_CACHED_RESPONSE_COMPLETE;
1525       next_state_ = STATE_CACHE_WRITE_RESPONSE;
1526       rv = OK;
1527     }
1528   }
1529   return rv;
1530 }
1531
1532 int HttpCache::Transaction::DoUpdateCachedResponseComplete(int result) {
1533   if (mode_ == UPDATE) {
1534     DCHECK(!handling_206_);
1535     // We got a "not modified" response and already updated the corresponding
1536     // cache entry above.
1537     //
1538     // By closing the cached entry now, we make sure that the 304 rather than
1539     // the cached 200 response, is what will be returned to the user.
1540     DoneWritingToEntry(true);
1541   } else if (entry_ && !handling_206_) {
1542     DCHECK_EQ(READ_WRITE, mode_);
1543     if (!partial_.get() || partial_->IsLastRange()) {
1544       cache_->ConvertWriterToReader(entry_);
1545       mode_ = READ;
1546     }
1547     // We no longer need the network transaction, so destroy it.
1548     final_upload_progress_ = network_trans_->GetUploadProgress();
1549     ResetNetworkTransaction();
1550   } else if (entry_ && handling_206_ && truncated_ &&
1551              partial_->initial_validation()) {
1552     // We just finished the validation of a truncated entry, and the server
1553     // is willing to resume the operation. Now we go back and start serving
1554     // the first part to the user.
1555     ResetNetworkTransaction();
1556     new_response_ = NULL;
1557     next_state_ = STATE_START_PARTIAL_CACHE_VALIDATION;
1558     partial_->SetRangeToStartDownload();
1559     return OK;
1560   }
1561   next_state_ = STATE_OVERWRITE_CACHED_RESPONSE;
1562   return OK;
1563 }
1564
1565 int HttpCache::Transaction::DoOverwriteCachedResponse() {
1566   if (mode_ & READ) {
1567     next_state_ = STATE_PARTIAL_HEADERS_RECEIVED;
1568     return OK;
1569   }
1570
1571   // We change the value of Content-Length for partial content.
1572   if (handling_206_ && partial_.get())
1573     partial_->FixContentLength(new_response_->headers.get());
1574
1575   response_ = *new_response_;
1576
1577   if (request_->method == "HEAD") {
1578     // This response is replacing the cached one.
1579     DoneWritingToEntry(false);
1580     mode_ = NONE;
1581     new_response_ = NULL;
1582     return OK;
1583   }
1584
1585   target_state_ = STATE_TRUNCATE_CACHED_DATA;
1586   next_state_ = truncated_ ? STATE_CACHE_WRITE_TRUNCATED_RESPONSE :
1587                              STATE_CACHE_WRITE_RESPONSE;
1588   return OK;
1589 }
1590
1591 int HttpCache::Transaction::DoTruncateCachedData() {
1592   next_state_ = STATE_TRUNCATE_CACHED_DATA_COMPLETE;
1593   if (!entry_)
1594     return OK;
1595   if (net_log_.IsLogging())
1596     net_log_.BeginEvent(NetLog::TYPE_HTTP_CACHE_WRITE_DATA);
1597   // Truncate the stream.
1598   return WriteToEntry(kResponseContentIndex, 0, NULL, 0, io_callback_);
1599 }
1600
1601 int HttpCache::Transaction::DoTruncateCachedDataComplete(int result) {
1602   if (entry_) {
1603     if (net_log_.IsLogging()) {
1604       net_log_.EndEventWithNetErrorCode(NetLog::TYPE_HTTP_CACHE_WRITE_DATA,
1605                                         result);
1606     }
1607   }
1608
1609   next_state_ = STATE_TRUNCATE_CACHED_METADATA;
1610   return OK;
1611 }
1612
1613 int HttpCache::Transaction::DoTruncateCachedMetadata() {
1614   next_state_ = STATE_TRUNCATE_CACHED_METADATA_COMPLETE;
1615   if (!entry_)
1616     return OK;
1617
1618   if (net_log_.IsLogging())
1619     net_log_.BeginEvent(NetLog::TYPE_HTTP_CACHE_WRITE_INFO);
1620   return WriteToEntry(kMetadataIndex, 0, NULL, 0, io_callback_);
1621 }
1622
1623 int HttpCache::Transaction::DoTruncateCachedMetadataComplete(int result) {
1624   if (entry_) {
1625     if (net_log_.IsLogging()) {
1626       net_log_.EndEventWithNetErrorCode(NetLog::TYPE_HTTP_CACHE_WRITE_INFO,
1627                                         result);
1628     }
1629   }
1630
1631   next_state_ = STATE_PARTIAL_HEADERS_RECEIVED;
1632   return OK;
1633 }
1634
1635 int HttpCache::Transaction::DoPartialHeadersReceived() {
1636   new_response_ = NULL;
1637   if (entry_ && !partial_.get() &&
1638       entry_->disk_entry->GetDataSize(kMetadataIndex))
1639     next_state_ = STATE_CACHE_READ_METADATA;
1640
1641   if (!partial_.get())
1642     return OK;
1643
1644   if (reading_) {
1645     if (network_trans_.get()) {
1646       next_state_ = STATE_NETWORK_READ;
1647     } else {
1648       next_state_ = STATE_CACHE_READ_DATA;
1649     }
1650   } else if (mode_ != NONE) {
1651     // We are about to return the headers for a byte-range request to the user,
1652     // so let's fix them.
1653     partial_->FixResponseHeaders(response_.headers.get(), true);
1654   }
1655   return OK;
1656 }
1657
1658 int HttpCache::Transaction::DoCacheReadResponse() {
1659   DCHECK(entry_);
1660   next_state_ = STATE_CACHE_READ_RESPONSE_COMPLETE;
1661
1662   io_buf_len_ = entry_->disk_entry->GetDataSize(kResponseInfoIndex);
1663   read_buf_ = new IOBuffer(io_buf_len_);
1664
1665   net_log_.BeginEvent(NetLog::TYPE_HTTP_CACHE_READ_INFO);
1666   return entry_->disk_entry->ReadData(kResponseInfoIndex, 0, read_buf_.get(),
1667                                       io_buf_len_, io_callback_);
1668 }
1669
1670 int HttpCache::Transaction::DoCacheReadResponseComplete(int result) {
1671   net_log_.EndEventWithNetErrorCode(NetLog::TYPE_HTTP_CACHE_READ_INFO, result);
1672   if (result != io_buf_len_ ||
1673       !HttpCache::ParseResponseInfo(read_buf_->data(), io_buf_len_,
1674                                     &response_, &truncated_)) {
1675     return OnCacheReadError(result, true);
1676   }
1677
1678   // cert_cache() will be null if the CertCacheTrial field trial is disabled.
1679   if (cache_->cert_cache() && response_.ssl_info.is_valid())
1680     ReadCertChain();
1681
1682   // Some resources may have slipped in as truncated when they're not.
1683   int current_size = entry_->disk_entry->GetDataSize(kResponseContentIndex);
1684   if (response_.headers->GetContentLength() == current_size)
1685     truncated_ = false;
1686
1687   // We now have access to the cache entry.
1688   //
1689   //  o if we are a reader for the transaction, then we can start reading the
1690   //    cache entry.
1691   //
1692   //  o if we can read or write, then we should check if the cache entry needs
1693   //    to be validated and then issue a network request if needed or just read
1694   //    from the cache if the cache entry is already valid.
1695   //
1696   //  o if we are set to UPDATE, then we are handling an externally
1697   //    conditionalized request (if-modified-since / if-none-match). We check
1698   //    if the request headers define a validation request.
1699   //
1700   switch (mode_) {
1701     case READ:
1702       UpdateTransactionPattern(PATTERN_ENTRY_USED);
1703       result = BeginCacheRead();
1704       break;
1705     case READ_WRITE:
1706       result = BeginPartialCacheValidation();
1707       break;
1708     case UPDATE:
1709       result = BeginExternallyConditionalizedRequest();
1710       break;
1711     case WRITE:
1712     default:
1713       NOTREACHED();
1714       result = ERR_FAILED;
1715   }
1716   return result;
1717 }
1718
1719 int HttpCache::Transaction::DoCacheWriteResponse() {
1720   if (entry_) {
1721     if (net_log_.IsLogging())
1722       net_log_.BeginEvent(NetLog::TYPE_HTTP_CACHE_WRITE_INFO);
1723   }
1724   return WriteResponseInfoToEntry(false);
1725 }
1726
1727 int HttpCache::Transaction::DoCacheWriteTruncatedResponse() {
1728   if (entry_) {
1729     if (net_log_.IsLogging())
1730       net_log_.BeginEvent(NetLog::TYPE_HTTP_CACHE_WRITE_INFO);
1731   }
1732   return WriteResponseInfoToEntry(true);
1733 }
1734
1735 int HttpCache::Transaction::DoCacheWriteResponseComplete(int result) {
1736   next_state_ = target_state_;
1737   target_state_ = STATE_NONE;
1738   if (!entry_)
1739     return OK;
1740   if (net_log_.IsLogging()) {
1741     net_log_.EndEventWithNetErrorCode(NetLog::TYPE_HTTP_CACHE_WRITE_INFO,
1742                                       result);
1743   }
1744
1745   // Balance the AddRef from WriteResponseInfoToEntry.
1746   if (result != io_buf_len_) {
1747     DLOG(ERROR) << "failed to write response info to cache";
1748     DoneWritingToEntry(false);
1749   }
1750   return OK;
1751 }
1752
1753 int HttpCache::Transaction::DoCacheReadMetadata() {
1754   DCHECK(entry_);
1755   DCHECK(!response_.metadata.get());
1756   next_state_ = STATE_CACHE_READ_METADATA_COMPLETE;
1757
1758   response_.metadata =
1759       new IOBufferWithSize(entry_->disk_entry->GetDataSize(kMetadataIndex));
1760
1761   net_log_.BeginEvent(NetLog::TYPE_HTTP_CACHE_READ_INFO);
1762   return entry_->disk_entry->ReadData(kMetadataIndex, 0,
1763                                       response_.metadata.get(),
1764                                       response_.metadata->size(),
1765                                       io_callback_);
1766 }
1767
1768 int HttpCache::Transaction::DoCacheReadMetadataComplete(int result) {
1769   net_log_.EndEventWithNetErrorCode(NetLog::TYPE_HTTP_CACHE_READ_INFO, result);
1770   if (result != response_.metadata->size())
1771     return OnCacheReadError(result, false);
1772   return OK;
1773 }
1774
1775 int HttpCache::Transaction::DoCacheQueryData() {
1776   next_state_ = STATE_CACHE_QUERY_DATA_COMPLETE;
1777   return entry_->disk_entry->ReadyForSparseIO(io_callback_);
1778 }
1779
1780 int HttpCache::Transaction::DoCacheQueryDataComplete(int result) {
1781   if (result == ERR_NOT_IMPLEMENTED) {
1782     // Restart the request overwriting the cache entry.
1783     // TODO(pasko): remove this workaround as soon as the SimpleBackendImpl
1784     // supports Sparse IO.
1785     return DoRestartPartialRequest();
1786   }
1787   DCHECK_EQ(OK, result);
1788   if (!cache_.get())
1789     return ERR_UNEXPECTED;
1790
1791   return ValidateEntryHeadersAndContinue();
1792 }
1793
1794 int HttpCache::Transaction::DoCacheReadData() {
1795   DCHECK(entry_);
1796   next_state_ = STATE_CACHE_READ_DATA_COMPLETE;
1797
1798   if (net_log_.IsLogging())
1799     net_log_.BeginEvent(NetLog::TYPE_HTTP_CACHE_READ_DATA);
1800   if (partial_.get()) {
1801     return partial_->CacheRead(entry_->disk_entry, read_buf_.get(), io_buf_len_,
1802                                io_callback_);
1803   }
1804
1805   return entry_->disk_entry->ReadData(kResponseContentIndex, read_offset_,
1806                                       read_buf_.get(), io_buf_len_,
1807                                       io_callback_);
1808 }
1809
1810 int HttpCache::Transaction::DoCacheReadDataComplete(int result) {
1811   if (net_log_.IsLogging()) {
1812     net_log_.EndEventWithNetErrorCode(NetLog::TYPE_HTTP_CACHE_READ_DATA,
1813                                       result);
1814   }
1815
1816   if (!cache_.get())
1817     return ERR_UNEXPECTED;
1818
1819   if (partial_.get()) {
1820     // Partial requests are confusing to report in histograms because they may
1821     // have multiple underlying requests.
1822     UpdateTransactionPattern(PATTERN_NOT_COVERED);
1823     return DoPartialCacheReadCompleted(result);
1824   }
1825
1826   if (result > 0) {
1827     read_offset_ += result;
1828   } else if (result == 0) {  // End of file.
1829     RecordHistograms();
1830     cache_->DoneReadingFromEntry(entry_, this);
1831     entry_ = NULL;
1832   } else {
1833     return OnCacheReadError(result, false);
1834   }
1835   return result;
1836 }
1837
1838 int HttpCache::Transaction::DoCacheWriteData(int num_bytes) {
1839   next_state_ = STATE_CACHE_WRITE_DATA_COMPLETE;
1840   write_len_ = num_bytes;
1841   if (entry_) {
1842     if (net_log_.IsLogging())
1843       net_log_.BeginEvent(NetLog::TYPE_HTTP_CACHE_WRITE_DATA);
1844   }
1845
1846   return AppendResponseDataToEntry(read_buf_.get(), num_bytes, io_callback_);
1847 }
1848
1849 int HttpCache::Transaction::DoCacheWriteDataComplete(int result) {
1850   if (entry_) {
1851     if (net_log_.IsLogging()) {
1852       net_log_.EndEventWithNetErrorCode(NetLog::TYPE_HTTP_CACHE_WRITE_DATA,
1853                                         result);
1854     }
1855   }
1856   // Balance the AddRef from DoCacheWriteData.
1857   if (!cache_.get())
1858     return ERR_UNEXPECTED;
1859
1860   if (result != write_len_) {
1861     DLOG(ERROR) << "failed to write response data to cache";
1862     DoneWritingToEntry(false);
1863
1864     // We want to ignore errors writing to disk and just keep reading from
1865     // the network.
1866     result = write_len_;
1867   } else if (!done_reading_ && entry_) {
1868     int current_size = entry_->disk_entry->GetDataSize(kResponseContentIndex);
1869     int64 body_size = response_.headers->GetContentLength();
1870     if (body_size >= 0 && body_size <= current_size)
1871       done_reading_ = true;
1872   }
1873
1874   if (partial_.get()) {
1875     // This may be the last request.
1876     if (!(result == 0 && !truncated_ &&
1877           (partial_->IsLastRange() || mode_ == WRITE)))
1878       return DoPartialNetworkReadCompleted(result);
1879   }
1880
1881   if (result == 0) {
1882     // End of file. This may be the result of a connection problem so see if we
1883     // have to keep the entry around to be flagged as truncated later on.
1884     if (done_reading_ || !entry_ || partial_.get() ||
1885         response_.headers->GetContentLength() <= 0)
1886       DoneWritingToEntry(true);
1887   }
1888
1889   return result;
1890 }
1891
1892 //-----------------------------------------------------------------------------
1893
1894 void HttpCache::Transaction::ReadCertChain() {
1895   std::string key =
1896       GetCacheKeyForCert(response_.ssl_info.cert->os_cert_handle());
1897   const X509Certificate::OSCertHandles& intermediates =
1898       response_.ssl_info.cert->GetIntermediateCertificates();
1899   int dist_from_root = intermediates.size();
1900
1901   scoped_refptr<SharedChainData> shared_chain_data(
1902       new SharedChainData(intermediates.size() + 1, TimeTicks::Now()));
1903   cache_->cert_cache()->GetCertificate(key,
1904                                        base::Bind(&OnCertReadIOComplete,
1905                                                   dist_from_root,
1906                                                   true /* is leaf */,
1907                                                   shared_chain_data));
1908
1909   for (X509Certificate::OSCertHandles::const_iterator it =
1910            intermediates.begin();
1911        it != intermediates.end();
1912        ++it) {
1913     --dist_from_root;
1914     key = GetCacheKeyForCert(*it);
1915     cache_->cert_cache()->GetCertificate(key,
1916                                          base::Bind(&OnCertReadIOComplete,
1917                                                     dist_from_root,
1918                                                     false /* is not leaf */,
1919                                                     shared_chain_data));
1920   }
1921   DCHECK_EQ(0, dist_from_root);
1922 }
1923
1924 void HttpCache::Transaction::WriteCertChain() {
1925   const X509Certificate::OSCertHandles& intermediates =
1926       response_.ssl_info.cert->GetIntermediateCertificates();
1927   int dist_from_root = intermediates.size();
1928
1929   scoped_refptr<SharedChainData> shared_chain_data(
1930       new SharedChainData(intermediates.size() + 1, TimeTicks::Now()));
1931   cache_->cert_cache()->SetCertificate(
1932       response_.ssl_info.cert->os_cert_handle(),
1933       base::Bind(&OnCertWriteIOComplete,
1934                  dist_from_root,
1935                  true /* is leaf */,
1936                  shared_chain_data));
1937   for (X509Certificate::OSCertHandles::const_iterator it =
1938            intermediates.begin();
1939        it != intermediates.end();
1940        ++it) {
1941     --dist_from_root;
1942     cache_->cert_cache()->SetCertificate(*it,
1943                                          base::Bind(&OnCertWriteIOComplete,
1944                                                     dist_from_root,
1945                                                     false /* is not leaf */,
1946                                                     shared_chain_data));
1947   }
1948   DCHECK_EQ(0, dist_from_root);
1949 }
1950
1951 void HttpCache::Transaction::SetRequest(const BoundNetLog& net_log,
1952                                         const HttpRequestInfo* request) {
1953   net_log_ = net_log;
1954   request_ = request;
1955   effective_load_flags_ = request_->load_flags;
1956
1957   switch (cache_->mode()) {
1958     case NORMAL:
1959       break;
1960     case RECORD:
1961       // When in record mode, we want to NEVER load from the cache.
1962       // The reason for this is because we save the Set-Cookie headers
1963       // (intentionally).  If we read from the cache, we replay them
1964       // prematurely.
1965       effective_load_flags_ |= LOAD_BYPASS_CACHE;
1966       break;
1967     case PLAYBACK:
1968       // When in playback mode, we want to load exclusively from the cache.
1969       effective_load_flags_ |= LOAD_ONLY_FROM_CACHE;
1970       break;
1971     case DISABLE:
1972       effective_load_flags_ |= LOAD_DISABLE_CACHE;
1973       break;
1974   }
1975
1976   // Some headers imply load flags.  The order here is significant.
1977   //
1978   //   LOAD_DISABLE_CACHE   : no cache read or write
1979   //   LOAD_BYPASS_CACHE    : no cache read
1980   //   LOAD_VALIDATE_CACHE  : no cache read unless validation
1981   //
1982   // The former modes trump latter modes, so if we find a matching header we
1983   // can stop iterating kSpecialHeaders.
1984   //
1985   static const struct {
1986     const HeaderNameAndValue* search;
1987     int load_flag;
1988   } kSpecialHeaders[] = {
1989     { kPassThroughHeaders, LOAD_DISABLE_CACHE },
1990     { kForceFetchHeaders, LOAD_BYPASS_CACHE },
1991     { kForceValidateHeaders, LOAD_VALIDATE_CACHE },
1992   };
1993
1994   bool range_found = false;
1995   bool external_validation_error = false;
1996
1997   if (request_->extra_headers.HasHeader(HttpRequestHeaders::kRange))
1998     range_found = true;
1999
2000   for (size_t i = 0; i < arraysize(kSpecialHeaders); ++i) {
2001     if (HeaderMatches(request_->extra_headers, kSpecialHeaders[i].search)) {
2002       effective_load_flags_ |= kSpecialHeaders[i].load_flag;
2003       break;
2004     }
2005   }
2006
2007   // Check for conditionalization headers which may correspond with a
2008   // cache validation request.
2009   for (size_t i = 0; i < arraysize(kValidationHeaders); ++i) {
2010     const ValidationHeaderInfo& info = kValidationHeaders[i];
2011     std::string validation_value;
2012     if (request_->extra_headers.GetHeader(
2013             info.request_header_name, &validation_value)) {
2014       if (!external_validation_.values[i].empty() ||
2015           validation_value.empty()) {
2016         external_validation_error = true;
2017       }
2018       external_validation_.values[i] = validation_value;
2019       external_validation_.initialized = true;
2020     }
2021   }
2022
2023   // We don't support ranges and validation headers.
2024   if (range_found && external_validation_.initialized) {
2025     LOG(WARNING) << "Byte ranges AND validation headers found.";
2026     effective_load_flags_ |= LOAD_DISABLE_CACHE;
2027   }
2028
2029   // If there is more than one validation header, we can't treat this request as
2030   // a cache validation, since we don't know for sure which header the server
2031   // will give us a response for (and they could be contradictory).
2032   if (external_validation_error) {
2033     LOG(WARNING) << "Multiple or malformed validation headers found.";
2034     effective_load_flags_ |= LOAD_DISABLE_CACHE;
2035   }
2036
2037   if (range_found && !(effective_load_flags_ & LOAD_DISABLE_CACHE)) {
2038     UpdateTransactionPattern(PATTERN_NOT_COVERED);
2039     partial_.reset(new PartialData);
2040     if (request_->method == "GET" && partial_->Init(request_->extra_headers)) {
2041       // We will be modifying the actual range requested to the server, so
2042       // let's remove the header here.
2043       custom_request_.reset(new HttpRequestInfo(*request_));
2044       custom_request_->extra_headers.RemoveHeader(HttpRequestHeaders::kRange);
2045       request_ = custom_request_.get();
2046       partial_->SetHeaders(custom_request_->extra_headers);
2047     } else {
2048       // The range is invalid or we cannot handle it properly.
2049       VLOG(1) << "Invalid byte range found.";
2050       effective_load_flags_ |= LOAD_DISABLE_CACHE;
2051       partial_.reset(NULL);
2052     }
2053   }
2054 }
2055
2056 bool HttpCache::Transaction::ShouldPassThrough() {
2057   // We may have a null disk_cache if there is an error we cannot recover from,
2058   // like not enough disk space, or sharing violations.
2059   if (!cache_->disk_cache_.get())
2060     return true;
2061
2062   // When using the record/playback modes, we always use the cache
2063   // and we never pass through.
2064   if (cache_->mode() == RECORD || cache_->mode() == PLAYBACK)
2065     return false;
2066
2067   if (effective_load_flags_ & LOAD_DISABLE_CACHE)
2068     return true;
2069
2070   if (request_->method == "GET" || request_->method == "HEAD")
2071     return false;
2072
2073   if (request_->method == "POST" && request_->upload_data_stream &&
2074       request_->upload_data_stream->identifier()) {
2075     return false;
2076   }
2077
2078   if (request_->method == "PUT" && request_->upload_data_stream)
2079     return false;
2080
2081   if (request_->method == "DELETE")
2082     return false;
2083
2084   return true;
2085 }
2086
2087 int HttpCache::Transaction::BeginCacheRead() {
2088   // We don't support any combination of LOAD_ONLY_FROM_CACHE and byte ranges.
2089   if (response_.headers->response_code() == 206 || partial_.get()) {
2090     NOTREACHED();
2091     return ERR_CACHE_MISS;
2092   }
2093
2094   if (request_->method == "HEAD")
2095     FixHeadersForHead();
2096
2097   // We don't have the whole resource.
2098   if (truncated_)
2099     return ERR_CACHE_MISS;
2100
2101   if (entry_->disk_entry->GetDataSize(kMetadataIndex))
2102     next_state_ = STATE_CACHE_READ_METADATA;
2103
2104   return OK;
2105 }
2106
2107 int HttpCache::Transaction::BeginCacheValidation() {
2108   DCHECK(mode_ == READ_WRITE);
2109
2110   ValidationType required_validation = RequiresValidation();
2111
2112   bool skip_validation = (required_validation == VALIDATION_NONE);
2113
2114   if (required_validation == VALIDATION_ASYNCHRONOUS &&
2115       !(request_->method == "GET" && (truncated_ || partial_)) && cache_ &&
2116       cache_->use_stale_while_revalidate()) {
2117     TriggerAsyncValidation();
2118     skip_validation = true;
2119   }
2120
2121   if (request_->method == "HEAD" &&
2122       (truncated_ || response_.headers->response_code() == 206)) {
2123     DCHECK(!partial_);
2124     if (skip_validation)
2125       return SetupEntryForRead();
2126
2127     // Bail out!
2128     next_state_ = STATE_SEND_REQUEST;
2129     mode_ = NONE;
2130     return OK;
2131   }
2132
2133   if (truncated_) {
2134     // Truncated entries can cause partial gets, so we shouldn't record this
2135     // load in histograms.
2136     UpdateTransactionPattern(PATTERN_NOT_COVERED);
2137     skip_validation = !partial_->initial_validation();
2138   }
2139
2140   if (partial_.get() && (is_sparse_ || truncated_) &&
2141       (!partial_->IsCurrentRangeCached() || invalid_range_)) {
2142     // Force revalidation for sparse or truncated entries. Note that we don't
2143     // want to ignore the regular validation logic just because a byte range was
2144     // part of the request.
2145     skip_validation = false;
2146   }
2147
2148   if (skip_validation) {
2149     // TODO(ricea): Is this pattern okay for asynchronous revalidations?
2150     UpdateTransactionPattern(PATTERN_ENTRY_USED);
2151     RecordOfflineStatus(effective_load_flags_, OFFLINE_STATUS_FRESH_CACHE);
2152     return SetupEntryForRead();
2153   } else {
2154     // Make the network request conditional, to see if we may reuse our cached
2155     // response.  If we cannot do so, then we just resort to a normal fetch.
2156     // Our mode remains READ_WRITE for a conditional request.  Even if the
2157     // conditionalization fails, we don't switch to WRITE mode until we
2158     // know we won't be falling back to using the cache entry in the
2159     // LOAD_FROM_CACHE_IF_OFFLINE case.
2160     if (!ConditionalizeRequest()) {
2161       couldnt_conditionalize_request_ = true;
2162       UpdateTransactionPattern(PATTERN_ENTRY_CANT_CONDITIONALIZE);
2163       if (partial_.get())
2164         return DoRestartPartialRequest();
2165
2166       DCHECK_NE(206, response_.headers->response_code());
2167     }
2168     next_state_ = STATE_SEND_REQUEST;
2169   }
2170   return OK;
2171 }
2172
2173 int HttpCache::Transaction::BeginPartialCacheValidation() {
2174   DCHECK(mode_ == READ_WRITE);
2175
2176   if (response_.headers->response_code() != 206 && !partial_.get() &&
2177       !truncated_) {
2178     return BeginCacheValidation();
2179   }
2180
2181   // Partial requests should not be recorded in histograms.
2182   UpdateTransactionPattern(PATTERN_NOT_COVERED);
2183   if (range_requested_) {
2184     next_state_ = STATE_CACHE_QUERY_DATA;
2185     return OK;
2186   }
2187
2188   // The request is not for a range, but we have stored just ranges.
2189
2190   if (request_->method == "HEAD")
2191     return BeginCacheValidation();
2192
2193   partial_.reset(new PartialData());
2194   partial_->SetHeaders(request_->extra_headers);
2195   if (!custom_request_.get()) {
2196     custom_request_.reset(new HttpRequestInfo(*request_));
2197     request_ = custom_request_.get();
2198   }
2199
2200   return ValidateEntryHeadersAndContinue();
2201 }
2202
2203 // This should only be called once per request.
2204 int HttpCache::Transaction::ValidateEntryHeadersAndContinue() {
2205   DCHECK(mode_ == READ_WRITE);
2206
2207   if (!partial_->UpdateFromStoredHeaders(
2208           response_.headers.get(), entry_->disk_entry, truncated_)) {
2209     return DoRestartPartialRequest();
2210   }
2211
2212   if (response_.headers->response_code() == 206)
2213     is_sparse_ = true;
2214
2215   if (!partial_->IsRequestedRangeOK()) {
2216     // The stored data is fine, but the request may be invalid.
2217     invalid_range_ = true;
2218   }
2219
2220   next_state_ = STATE_START_PARTIAL_CACHE_VALIDATION;
2221   return OK;
2222 }
2223
2224 int HttpCache::Transaction::BeginExternallyConditionalizedRequest() {
2225   DCHECK_EQ(UPDATE, mode_);
2226   DCHECK(external_validation_.initialized);
2227
2228   for (size_t i = 0;  i < arraysize(kValidationHeaders); i++) {
2229     if (external_validation_.values[i].empty())
2230       continue;
2231     // Retrieve either the cached response's "etag" or "last-modified" header.
2232     std::string validator;
2233     response_.headers->EnumerateHeader(
2234         NULL,
2235         kValidationHeaders[i].related_response_header_name,
2236         &validator);
2237
2238     if (response_.headers->response_code() != 200 || truncated_ ||
2239         validator.empty() || validator != external_validation_.values[i]) {
2240       // The externally conditionalized request is not a validation request
2241       // for our existing cache entry. Proceed with caching disabled.
2242       UpdateTransactionPattern(PATTERN_NOT_COVERED);
2243       DoneWritingToEntry(true);
2244     }
2245   }
2246
2247   // TODO(ricea): This calculation is expensive to perform just to collect
2248   // statistics. Either remove it or use the result, depending on the result of
2249   // the experiment.
2250   ExternallyConditionalizedType type =
2251       EXTERNALLY_CONDITIONALIZED_CACHE_USABLE;
2252   if (mode_ == NONE)
2253     type = EXTERNALLY_CONDITIONALIZED_MISMATCHED_VALIDATORS;
2254   else if (RequiresValidation())
2255     type = EXTERNALLY_CONDITIONALIZED_CACHE_REQUIRES_VALIDATION;
2256
2257   // TODO(ricea): Add CACHE_USABLE_STALE once stale-while-revalidate CL landed.
2258   // TODO(ricea): Either remove this histogram or make it permanent by M40.
2259   UMA_HISTOGRAM_ENUMERATION("HttpCache.ExternallyConditionalized",
2260                             type,
2261                             EXTERNALLY_CONDITIONALIZED_MAX);
2262
2263   next_state_ = STATE_SEND_REQUEST;
2264   return OK;
2265 }
2266
2267 int HttpCache::Transaction::RestartNetworkRequest() {
2268   DCHECK(mode_ & WRITE || mode_ == NONE);
2269   DCHECK(network_trans_.get());
2270   DCHECK_EQ(STATE_NONE, next_state_);
2271
2272   next_state_ = STATE_SEND_REQUEST_COMPLETE;
2273   int rv = network_trans_->RestartIgnoringLastError(io_callback_);
2274   if (rv != ERR_IO_PENDING)
2275     return DoLoop(rv);
2276   return rv;
2277 }
2278
2279 int HttpCache::Transaction::RestartNetworkRequestWithCertificate(
2280     X509Certificate* client_cert) {
2281   DCHECK(mode_ & WRITE || mode_ == NONE);
2282   DCHECK(network_trans_.get());
2283   DCHECK_EQ(STATE_NONE, next_state_);
2284
2285   next_state_ = STATE_SEND_REQUEST_COMPLETE;
2286   int rv = network_trans_->RestartWithCertificate(client_cert, io_callback_);
2287   if (rv != ERR_IO_PENDING)
2288     return DoLoop(rv);
2289   return rv;
2290 }
2291
2292 int HttpCache::Transaction::RestartNetworkRequestWithAuth(
2293     const AuthCredentials& credentials) {
2294   DCHECK(mode_ & WRITE || mode_ == NONE);
2295   DCHECK(network_trans_.get());
2296   DCHECK_EQ(STATE_NONE, next_state_);
2297
2298   next_state_ = STATE_SEND_REQUEST_COMPLETE;
2299   int rv = network_trans_->RestartWithAuth(credentials, io_callback_);
2300   if (rv != ERR_IO_PENDING)
2301     return DoLoop(rv);
2302   return rv;
2303 }
2304
2305 ValidationType HttpCache::Transaction::RequiresValidation() {
2306   // TODO(darin): need to do more work here:
2307   //  - make sure we have a matching request method
2308   //  - watch out for cached responses that depend on authentication
2309
2310   // In playback mode, nothing requires validation.
2311   if (cache_->mode() == net::HttpCache::PLAYBACK)
2312     return VALIDATION_NONE;
2313
2314   if (response_.vary_data.is_valid() &&
2315       !response_.vary_data.MatchesRequest(*request_,
2316                                           *response_.headers.get())) {
2317     vary_mismatch_ = true;
2318     return VALIDATION_SYNCHRONOUS;
2319   }
2320
2321   if (effective_load_flags_ & LOAD_PREFERRING_CACHE)
2322     return VALIDATION_NONE;
2323
2324   if (effective_load_flags_ & (LOAD_VALIDATE_CACHE | LOAD_ASYNC_REVALIDATION))
2325     return VALIDATION_SYNCHRONOUS;
2326
2327   if (request_->method == "PUT" || request_->method == "DELETE")
2328     return VALIDATION_SYNCHRONOUS;
2329
2330   ValidationType validation_required_by_headers =
2331       response_.headers->RequiresValidation(
2332           response_.request_time, response_.response_time, Time::Now());
2333
2334   if (validation_required_by_headers == VALIDATION_ASYNCHRONOUS) {
2335     // Asynchronous revalidation is only supported for GET and HEAD methods.
2336     if (request_->method != "GET" && request_->method != "HEAD")
2337       return VALIDATION_SYNCHRONOUS;
2338   }
2339
2340   return validation_required_by_headers;
2341 }
2342
2343 bool HttpCache::Transaction::ConditionalizeRequest() {
2344   DCHECK(response_.headers.get());
2345
2346   if (request_->method == "PUT" || request_->method == "DELETE")
2347     return false;
2348
2349   // This only makes sense for cached 200 or 206 responses.
2350   if (response_.headers->response_code() != 200 &&
2351       response_.headers->response_code() != 206) {
2352     return false;
2353   }
2354
2355   if (response_.headers->response_code() == 206 &&
2356       !response_.headers->HasStrongValidators()) {
2357     return false;
2358   }
2359
2360   // Just use the first available ETag and/or Last-Modified header value.
2361   // TODO(darin): Or should we use the last?
2362
2363   std::string etag_value;
2364   if (response_.headers->GetHttpVersion() >= HttpVersion(1, 1))
2365     response_.headers->EnumerateHeader(NULL, "etag", &etag_value);
2366
2367   std::string last_modified_value;
2368   if (!vary_mismatch_) {
2369     response_.headers->EnumerateHeader(NULL, "last-modified",
2370                                        &last_modified_value);
2371   }
2372
2373   if (etag_value.empty() && last_modified_value.empty())
2374     return false;
2375
2376   if (!partial_.get()) {
2377     // Need to customize the request, so this forces us to allocate :(
2378     custom_request_.reset(new HttpRequestInfo(*request_));
2379     request_ = custom_request_.get();
2380   }
2381   DCHECK(custom_request_.get());
2382
2383   bool use_if_range = partial_.get() && !partial_->IsCurrentRangeCached() &&
2384                       !invalid_range_;
2385
2386   if (!use_if_range) {
2387     // stale-while-revalidate is not useful when we only have a partial response
2388     // cached, so don't set the header in that case.
2389     HttpResponseHeaders::FreshnessLifetimes lifetimes =
2390         response_.headers->GetFreshnessLifetimes(response_.response_time);
2391     if (lifetimes.staleness > TimeDelta()) {
2392       TimeDelta current_age = response_.headers->GetCurrentAge(
2393           response_.request_time, response_.response_time, Time::Now());
2394
2395       custom_request_->extra_headers.SetHeader(
2396           kFreshnessHeader,
2397           base::StringPrintf("max-age=%" PRId64
2398                              ",stale-while-revalidate=%" PRId64 ",age=%" PRId64,
2399                              lifetimes.freshness.InSeconds(),
2400                              lifetimes.staleness.InSeconds(),
2401                              current_age.InSeconds()));
2402     }
2403   }
2404
2405   if (!etag_value.empty()) {
2406     if (use_if_range) {
2407       // We don't want to switch to WRITE mode if we don't have this block of a
2408       // byte-range request because we may have other parts cached.
2409       custom_request_->extra_headers.SetHeader(
2410           HttpRequestHeaders::kIfRange, etag_value);
2411     } else {
2412       custom_request_->extra_headers.SetHeader(
2413           HttpRequestHeaders::kIfNoneMatch, etag_value);
2414     }
2415     // For byte-range requests, make sure that we use only one way to validate
2416     // the request.
2417     if (partial_.get() && !partial_->IsCurrentRangeCached())
2418       return true;
2419   }
2420
2421   if (!last_modified_value.empty()) {
2422     if (use_if_range) {
2423       custom_request_->extra_headers.SetHeader(
2424           HttpRequestHeaders::kIfRange, last_modified_value);
2425     } else {
2426       custom_request_->extra_headers.SetHeader(
2427           HttpRequestHeaders::kIfModifiedSince, last_modified_value);
2428     }
2429   }
2430
2431   return true;
2432 }
2433
2434 // We just received some headers from the server. We may have asked for a range,
2435 // in which case partial_ has an object. This could be the first network request
2436 // we make to fulfill the original request, or we may be already reading (from
2437 // the net and / or the cache). If we are not expecting a certain response, we
2438 // just bypass the cache for this request (but again, maybe we are reading), and
2439 // delete partial_ (so we are not able to "fix" the headers that we return to
2440 // the user). This results in either a weird response for the caller (we don't
2441 // expect it after all), or maybe a range that was not exactly what it was asked
2442 // for.
2443 //
2444 // If the server is simply telling us that the resource has changed, we delete
2445 // the cached entry and restart the request as the caller intended (by returning
2446 // false from this method). However, we may not be able to do that at any point,
2447 // for instance if we already returned the headers to the user.
2448 //
2449 // WARNING: Whenever this code returns false, it has to make sure that the next
2450 // time it is called it will return true so that we don't keep retrying the
2451 // request.
2452 bool HttpCache::Transaction::ValidatePartialResponse() {
2453   const HttpResponseHeaders* headers = new_response_->headers.get();
2454   int response_code = headers->response_code();
2455   bool partial_response = (response_code == 206);
2456   handling_206_ = false;
2457
2458   if (!entry_ || request_->method != "GET")
2459     return true;
2460
2461   if (invalid_range_) {
2462     // We gave up trying to match this request with the stored data. If the
2463     // server is ok with the request, delete the entry, otherwise just ignore
2464     // this request
2465     DCHECK(!reading_);
2466     if (partial_response || response_code == 200) {
2467       DoomPartialEntry(true);
2468       mode_ = NONE;
2469     } else {
2470       if (response_code == 304)
2471         FailRangeRequest();
2472       IgnoreRangeRequest();
2473     }
2474     return true;
2475   }
2476
2477   if (!partial_.get()) {
2478     // We are not expecting 206 but we may have one.
2479     if (partial_response)
2480       IgnoreRangeRequest();
2481
2482     return true;
2483   }
2484
2485   // TODO(rvargas): Do we need to consider other results here?.
2486   bool failure = response_code == 200 || response_code == 416;
2487
2488   if (partial_->IsCurrentRangeCached()) {
2489     // We asked for "If-None-Match: " so a 206 means a new object.
2490     if (partial_response)
2491       failure = true;
2492
2493     if (response_code == 304 && partial_->ResponseHeadersOK(headers))
2494       return true;
2495   } else {
2496     // We asked for "If-Range: " so a 206 means just another range.
2497     if (partial_response && partial_->ResponseHeadersOK(headers)) {
2498       handling_206_ = true;
2499       return true;
2500     }
2501
2502     if (!reading_ && !is_sparse_ && !partial_response) {
2503       // See if we can ignore the fact that we issued a byte range request.
2504       // If the server sends 200, just store it. If it sends an error, redirect
2505       // or something else, we may store the response as long as we didn't have
2506       // anything already stored.
2507       if (response_code == 200 ||
2508           (!truncated_ && response_code != 304 && response_code != 416)) {
2509         // The server is sending something else, and we can save it.
2510         DCHECK((truncated_ && !partial_->IsLastRange()) || range_requested_);
2511         partial_.reset();
2512         truncated_ = false;
2513         return true;
2514       }
2515     }
2516
2517     // 304 is not expected here, but we'll spare the entry (unless it was
2518     // truncated).
2519     if (truncated_)
2520       failure = true;
2521   }
2522
2523   if (failure) {
2524     // We cannot truncate this entry, it has to be deleted.
2525     UpdateTransactionPattern(PATTERN_NOT_COVERED);
2526     DoomPartialEntry(false);
2527     mode_ = NONE;
2528     if (!reading_ && !partial_->IsLastRange()) {
2529       // We'll attempt to issue another network request, this time without us
2530       // messing up the headers.
2531       partial_->RestoreHeaders(&custom_request_->extra_headers);
2532       partial_.reset();
2533       truncated_ = false;
2534       return false;
2535     }
2536     LOG(WARNING) << "Failed to revalidate partial entry";
2537     partial_.reset();
2538     return true;
2539   }
2540
2541   IgnoreRangeRequest();
2542   return true;
2543 }
2544
2545 void HttpCache::Transaction::IgnoreRangeRequest() {
2546   // We have a problem. We may or may not be reading already (in which case we
2547   // returned the headers), but we'll just pretend that this request is not
2548   // using the cache and see what happens. Most likely this is the first
2549   // response from the server (it's not changing its mind midway, right?).
2550   UpdateTransactionPattern(PATTERN_NOT_COVERED);
2551   if (mode_ & WRITE)
2552     DoneWritingToEntry(mode_ != WRITE);
2553   else if (mode_ & READ && entry_)
2554     cache_->DoneReadingFromEntry(entry_, this);
2555
2556   partial_.reset(NULL);
2557   entry_ = NULL;
2558   mode_ = NONE;
2559 }
2560
2561 void HttpCache::Transaction::FixHeadersForHead() {
2562   if (response_.headers->response_code() == 206) {
2563     response_.headers->RemoveHeader("Content-Length");
2564     response_.headers->RemoveHeader("Content-Range");
2565     response_.headers->ReplaceStatusLine("HTTP/1.1 200 OK");
2566   }
2567 }
2568
2569 void HttpCache::Transaction::TriggerAsyncValidation() {
2570   DCHECK(!request_->upload_data_stream);
2571   BoundNetLog async_revalidation_net_log(
2572       BoundNetLog::Make(net_log_.net_log(), NetLog::SOURCE_ASYNC_REVALIDATION));
2573   net_log_.AddEvent(
2574       NetLog::TYPE_HTTP_CACHE_VALIDATE_RESOURCE_ASYNC,
2575       async_revalidation_net_log.source().ToEventParametersCallback());
2576   async_revalidation_net_log.BeginEvent(
2577       NetLog::TYPE_ASYNC_REVALIDATION,
2578       base::Bind(
2579           &NetLogAsyncRevalidationInfoCallback, net_log_.source(), request_));
2580   base::MessageLoop::current()->PostTask(
2581       FROM_HERE,
2582       base::Bind(&HttpCache::PerformAsyncValidation,
2583                  cache_,  // cache_ is a weak pointer.
2584                  *request_,
2585                  async_revalidation_net_log));
2586 }
2587
2588 void HttpCache::Transaction::FailRangeRequest() {
2589   response_ = *new_response_;
2590   partial_->FixResponseHeaders(response_.headers.get(), false);
2591 }
2592
2593 int HttpCache::Transaction::SetupEntryForRead() {
2594   if (network_trans_)
2595     ResetNetworkTransaction();
2596   if (partial_.get()) {
2597     if (truncated_ || is_sparse_ || !invalid_range_) {
2598       // We are going to return the saved response headers to the caller, so
2599       // we may need to adjust them first.
2600       next_state_ = STATE_PARTIAL_HEADERS_RECEIVED;
2601       return OK;
2602     } else {
2603       partial_.reset();
2604     }
2605   }
2606   cache_->ConvertWriterToReader(entry_);
2607   mode_ = READ;
2608
2609   if (request_->method == "HEAD")
2610     FixHeadersForHead();
2611
2612   if (entry_->disk_entry->GetDataSize(kMetadataIndex))
2613     next_state_ = STATE_CACHE_READ_METADATA;
2614   return OK;
2615 }
2616
2617
2618 int HttpCache::Transaction::ReadFromNetwork(IOBuffer* data, int data_len) {
2619   read_buf_ = data;
2620   io_buf_len_ = data_len;
2621   next_state_ = STATE_NETWORK_READ;
2622   return DoLoop(OK);
2623 }
2624
2625 int HttpCache::Transaction::ReadFromEntry(IOBuffer* data, int data_len) {
2626   if (request_->method == "HEAD")
2627     return 0;
2628
2629   read_buf_ = data;
2630   io_buf_len_ = data_len;
2631   next_state_ = STATE_CACHE_READ_DATA;
2632   return DoLoop(OK);
2633 }
2634
2635 int HttpCache::Transaction::WriteToEntry(int index, int offset,
2636                                          IOBuffer* data, int data_len,
2637                                          const CompletionCallback& callback) {
2638   if (!entry_)
2639     return data_len;
2640
2641   int rv = 0;
2642   if (!partial_.get() || !data_len) {
2643     rv = entry_->disk_entry->WriteData(index, offset, data, data_len, callback,
2644                                        true);
2645   } else {
2646     rv = partial_->CacheWrite(entry_->disk_entry, data, data_len, callback);
2647   }
2648   return rv;
2649 }
2650
2651 int HttpCache::Transaction::WriteResponseInfoToEntry(bool truncated) {
2652   next_state_ = STATE_CACHE_WRITE_RESPONSE_COMPLETE;
2653   if (!entry_)
2654     return OK;
2655
2656   // Do not cache no-store content (unless we are record mode).  Do not cache
2657   // content with cert errors either.  This is to prevent not reporting net
2658   // errors when loading a resource from the cache.  When we load a page over
2659   // HTTPS with a cert error we show an SSL blocking page.  If the user clicks
2660   // proceed we reload the resource ignoring the errors.  The loaded resource
2661   // is then cached.  If that resource is subsequently loaded from the cache,
2662   // no net error is reported (even though the cert status contains the actual
2663   // errors) and no SSL blocking page is shown.  An alternative would be to
2664   // reverse-map the cert status to a net error and replay the net error.
2665   if ((cache_->mode() != RECORD &&
2666        response_.headers->HasHeaderValue("cache-control", "no-store")) ||
2667       net::IsCertStatusError(response_.ssl_info.cert_status)) {
2668     DoneWritingToEntry(false);
2669     if (net_log_.IsLogging())
2670       net_log_.EndEvent(NetLog::TYPE_HTTP_CACHE_WRITE_INFO);
2671     return OK;
2672   }
2673
2674   // cert_cache() will be null if the CertCacheTrial field trial is disabled.
2675   if (cache_->cert_cache() && response_.ssl_info.is_valid())
2676     WriteCertChain();
2677
2678   // When writing headers, we normally only write the non-transient
2679   // headers; when in record mode, record everything.
2680   bool skip_transient_headers = (cache_->mode() != RECORD);
2681
2682   if (truncated)
2683     DCHECK_EQ(200, response_.headers->response_code());
2684
2685   scoped_refptr<PickledIOBuffer> data(new PickledIOBuffer());
2686   response_.Persist(data->pickle(), skip_transient_headers, truncated);
2687   data->Done();
2688
2689   io_buf_len_ = data->pickle()->size();
2690   return entry_->disk_entry->WriteData(kResponseInfoIndex, 0, data.get(),
2691                                        io_buf_len_, io_callback_, true);
2692 }
2693
2694 int HttpCache::Transaction::AppendResponseDataToEntry(
2695     IOBuffer* data, int data_len, const CompletionCallback& callback) {
2696   if (!entry_ || !data_len)
2697     return data_len;
2698
2699   int current_size = entry_->disk_entry->GetDataSize(kResponseContentIndex);
2700   return WriteToEntry(kResponseContentIndex, current_size, data, data_len,
2701                       callback);
2702 }
2703
2704 void HttpCache::Transaction::DoneWritingToEntry(bool success) {
2705   if (!entry_)
2706     return;
2707
2708   RecordHistograms();
2709
2710   cache_->DoneWritingToEntry(entry_, success);
2711   entry_ = NULL;
2712   mode_ = NONE;  // switch to 'pass through' mode
2713 }
2714
2715 int HttpCache::Transaction::OnCacheReadError(int result, bool restart) {
2716   DLOG(ERROR) << "ReadData failed: " << result;
2717   const int result_for_histogram = std::max(0, -result);
2718   if (restart) {
2719     UMA_HISTOGRAM_SPARSE_SLOWLY("HttpCache.ReadErrorRestartable",
2720                                 result_for_histogram);
2721   } else {
2722     UMA_HISTOGRAM_SPARSE_SLOWLY("HttpCache.ReadErrorNonRestartable",
2723                                 result_for_histogram);
2724   }
2725
2726   // Avoid using this entry in the future.
2727   if (cache_.get())
2728     cache_->DoomActiveEntry(cache_key_);
2729
2730   if (restart) {
2731     DCHECK(!reading_);
2732     DCHECK(!network_trans_.get());
2733     cache_->DoneWithEntry(entry_, this, false);
2734     entry_ = NULL;
2735     is_sparse_ = false;
2736     partial_.reset();
2737     next_state_ = STATE_GET_BACKEND;
2738     return OK;
2739   }
2740
2741   return ERR_CACHE_READ_FAILURE;
2742 }
2743
2744 void HttpCache::Transaction::OnAddToEntryTimeout(base::TimeTicks start_time) {
2745   if (entry_lock_waiting_since_ != start_time)
2746     return;
2747
2748   DCHECK_EQ(next_state_, STATE_ADD_TO_ENTRY_COMPLETE);
2749
2750   if (!cache_)
2751     return;
2752
2753   cache_->RemovePendingTransaction(this);
2754   OnIOComplete(ERR_CACHE_LOCK_TIMEOUT);
2755 }
2756
2757 void HttpCache::Transaction::DoomPartialEntry(bool delete_object) {
2758   DVLOG(2) << "DoomPartialEntry";
2759   int rv = cache_->DoomEntry(cache_key_, NULL);
2760   DCHECK_EQ(OK, rv);
2761   cache_->DoneWithEntry(entry_, this, false);
2762   entry_ = NULL;
2763   is_sparse_ = false;
2764   if (delete_object)
2765     partial_.reset(NULL);
2766 }
2767
2768 int HttpCache::Transaction::DoPartialNetworkReadCompleted(int result) {
2769   partial_->OnNetworkReadCompleted(result);
2770
2771   if (result == 0) {
2772     // We need to move on to the next range.
2773     ResetNetworkTransaction();
2774     next_state_ = STATE_START_PARTIAL_CACHE_VALIDATION;
2775   }
2776   return result;
2777 }
2778
2779 int HttpCache::Transaction::DoPartialCacheReadCompleted(int result) {
2780   partial_->OnCacheReadCompleted(result);
2781
2782   if (result == 0 && mode_ == READ_WRITE) {
2783     // We need to move on to the next range.
2784     next_state_ = STATE_START_PARTIAL_CACHE_VALIDATION;
2785   } else if (result < 0) {
2786     return OnCacheReadError(result, false);
2787   }
2788   return result;
2789 }
2790
2791 int HttpCache::Transaction::DoRestartPartialRequest() {
2792   // The stored data cannot be used. Get rid of it and restart this request.
2793   // We need to also reset the |truncated_| flag as a new entry is created.
2794   DoomPartialEntry(!range_requested_);
2795   mode_ = WRITE;
2796   truncated_ = false;
2797   next_state_ = STATE_INIT_ENTRY;
2798   return OK;
2799 }
2800
2801 void HttpCache::Transaction::ResetNetworkTransaction() {
2802   DCHECK(!old_network_trans_load_timing_);
2803   DCHECK(network_trans_);
2804   LoadTimingInfo load_timing;
2805   if (network_trans_->GetLoadTimingInfo(&load_timing))
2806     old_network_trans_load_timing_.reset(new LoadTimingInfo(load_timing));
2807   total_received_bytes_ += network_trans_->GetTotalReceivedBytes();
2808   network_trans_.reset();
2809 }
2810
2811 // Histogram data from the end of 2010 show the following distribution of
2812 // response headers:
2813 //
2814 //   Content-Length............... 87%
2815 //   Date......................... 98%
2816 //   Last-Modified................ 49%
2817 //   Etag......................... 19%
2818 //   Accept-Ranges: bytes......... 25%
2819 //   Accept-Ranges: none.......... 0.4%
2820 //   Strong Validator............. 50%
2821 //   Strong Validator + ranges.... 24%
2822 //   Strong Validator + CL........ 49%
2823 //
2824 bool HttpCache::Transaction::CanResume(bool has_data) {
2825   // Double check that there is something worth keeping.
2826   if (has_data && !entry_->disk_entry->GetDataSize(kResponseContentIndex))
2827     return false;
2828
2829   if (request_->method != "GET")
2830     return false;
2831
2832   // Note that if this is a 206, content-length was already fixed after calling
2833   // PartialData::ResponseHeadersOK().
2834   if (response_.headers->GetContentLength() <= 0 ||
2835       response_.headers->HasHeaderValue("Accept-Ranges", "none") ||
2836       !response_.headers->HasStrongValidators()) {
2837     return false;
2838   }
2839
2840   return true;
2841 }
2842
2843 void HttpCache::Transaction::UpdateTransactionPattern(
2844     TransactionPattern new_transaction_pattern) {
2845   if (transaction_pattern_ == PATTERN_NOT_COVERED)
2846     return;
2847   DCHECK(transaction_pattern_ == PATTERN_UNDEFINED ||
2848          new_transaction_pattern == PATTERN_NOT_COVERED);
2849   transaction_pattern_ = new_transaction_pattern;
2850 }
2851
2852 void HttpCache::Transaction::RecordHistograms() {
2853   DCHECK_NE(PATTERN_UNDEFINED, transaction_pattern_);
2854   if (!cache_.get() || !cache_->GetCurrentBackend() ||
2855       cache_->GetCurrentBackend()->GetCacheType() != DISK_CACHE ||
2856       cache_->mode() != NORMAL || request_->method != "GET") {
2857     return;
2858   }
2859   UMA_HISTOGRAM_ENUMERATION(
2860       "HttpCache.Pattern", transaction_pattern_, PATTERN_MAX);
2861   if (transaction_pattern_ == PATTERN_NOT_COVERED)
2862     return;
2863   DCHECK(!range_requested_);
2864   DCHECK(!first_cache_access_since_.is_null());
2865
2866   TimeDelta total_time = base::TimeTicks::Now() - first_cache_access_since_;
2867
2868   UMA_HISTOGRAM_TIMES("HttpCache.AccessToDone", total_time);
2869
2870   bool did_send_request = !send_request_since_.is_null();
2871   DCHECK(
2872       (did_send_request &&
2873        (transaction_pattern_ == PATTERN_ENTRY_NOT_CACHED ||
2874         transaction_pattern_ == PATTERN_ENTRY_VALIDATED ||
2875         transaction_pattern_ == PATTERN_ENTRY_UPDATED ||
2876         transaction_pattern_ == PATTERN_ENTRY_CANT_CONDITIONALIZE)) ||
2877       (!did_send_request && transaction_pattern_ == PATTERN_ENTRY_USED));
2878
2879   if (!did_send_request) {
2880     DCHECK(transaction_pattern_ == PATTERN_ENTRY_USED);
2881     UMA_HISTOGRAM_TIMES("HttpCache.AccessToDone.Used", total_time);
2882     return;
2883   }
2884
2885   TimeDelta before_send_time = send_request_since_ - first_cache_access_since_;
2886   int before_send_percent =
2887       total_time.ToInternalValue() == 0 ? 0
2888                                         : before_send_time * 100 / total_time;
2889   DCHECK_LE(0, before_send_percent);
2890   DCHECK_GE(100, before_send_percent);
2891
2892   UMA_HISTOGRAM_TIMES("HttpCache.AccessToDone.SentRequest", total_time);
2893   UMA_HISTOGRAM_TIMES("HttpCache.BeforeSend", before_send_time);
2894   UMA_HISTOGRAM_PERCENTAGE("HttpCache.PercentBeforeSend", before_send_percent);
2895
2896   // TODO(gavinp): Remove or minimize these histograms, particularly the ones
2897   // below this comment after we have received initial data.
2898   switch (transaction_pattern_) {
2899     case PATTERN_ENTRY_CANT_CONDITIONALIZE: {
2900       UMA_HISTOGRAM_TIMES("HttpCache.BeforeSend.CantConditionalize",
2901                           before_send_time);
2902       UMA_HISTOGRAM_PERCENTAGE("HttpCache.PercentBeforeSend.CantConditionalize",
2903                                before_send_percent);
2904       break;
2905     }
2906     case PATTERN_ENTRY_NOT_CACHED: {
2907       UMA_HISTOGRAM_TIMES("HttpCache.BeforeSend.NotCached", before_send_time);
2908       UMA_HISTOGRAM_PERCENTAGE("HttpCache.PercentBeforeSend.NotCached",
2909                                before_send_percent);
2910       break;
2911     }
2912     case PATTERN_ENTRY_VALIDATED: {
2913       UMA_HISTOGRAM_TIMES("HttpCache.BeforeSend.Validated", before_send_time);
2914       UMA_HISTOGRAM_PERCENTAGE("HttpCache.PercentBeforeSend.Validated",
2915                                before_send_percent);
2916       break;
2917     }
2918     case PATTERN_ENTRY_UPDATED: {
2919       UMA_HISTOGRAM_TIMES("HttpCache.BeforeSend.Updated", before_send_time);
2920       UMA_HISTOGRAM_PERCENTAGE("HttpCache.PercentBeforeSend.Updated",
2921                                before_send_percent);
2922       break;
2923     }
2924     default:
2925       NOTREACHED();
2926   }
2927 }
2928
2929 void HttpCache::Transaction::OnIOComplete(int result) {
2930   // TODO(vadimt): Remove ScopedTracker below once crbug.com/422516 is fixed.
2931   tracked_objects::ScopedTracker tracking_profile(
2932       FROM_HERE_WITH_EXPLICIT_FUNCTION("422516 Transaction::OnIOComplete"));
2933
2934   DoLoop(result);
2935 }
2936
2937 }  // namespace net