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