forked from Pissandshittium/pissandshittium
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhttp_cache_transaction.cc
4036 lines (3493 loc) · 142 KB
/
http_cache_transaction.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "net/http/http_cache_transaction.h"
#include "build/build_config.h" // For IS_POSIX
#if BUILDFLAG(IS_POSIX)
#include <unistd.h>
#endif
#include <algorithm>
#include <memory>
#include <string>
#include <type_traits>
#include <utility>
#include "base/auto_reset.h"
#include "base/compiler_specific.h"
#include "base/containers/fixed_flat_set.h"
#include "base/feature_list.h"
#include "base/format_macros.h"
#include "base/functional/bind.h"
#include "base/functional/callback_helpers.h"
#include "base/location.h"
#include "base/memory/raw_ptr_exclusion.h"
#include "base/metrics/histogram_functions.h"
#include "base/metrics/histogram_macros.h"
#include "base/power_monitor/power_monitor.h"
#include "base/strings/string_piece.h"
#include "base/strings/string_util.h" // For EqualsCaseInsensitiveASCII.
#include "base/task/single_thread_task_runner.h"
#include "base/time/clock.h"
#include "base/trace_event/common/trace_event_common.h"
#include "base/values.h"
#include "net/base/auth.h"
#include "net/base/cache_metrics.h"
#include "net/base/features.h"
#include "net/base/load_flags.h"
#include "net/base/load_timing_info.h"
#include "net/base/trace_constants.h"
#include "net/base/tracing.h"
#include "net/base/transport_info.h"
#include "net/base/upload_data_stream.h"
#include "net/cert/cert_status_flags.h"
#include "net/cert/x509_certificate.h"
#include "net/disk_cache/disk_cache.h"
#include "net/http/http_cache_writers.h"
#include "net/http/http_log_util.h"
#include "net/http/http_network_session.h"
#include "net/http/http_request_info.h"
#include "net/http/http_response_headers.h"
#include "net/http/http_status_code.h"
#include "net/http/http_util.h"
#include "net/log/net_log_event_type.h"
#include "net/ssl/ssl_cert_request_info.h"
#include "net/ssl/ssl_config_service.h"
using base::Time;
using base::TimeTicks;
namespace net {
using CacheEntryStatus = HttpResponseInfo::CacheEntryStatus;
namespace {
constexpr base::TimeDelta kStaleRevalidateTimeout = base::Seconds(60);
uint64_t GetNextTraceId(HttpCache* cache) {
static uint32_t sNextTraceId = 0;
DCHECK(cache);
return (reinterpret_cast<uint64_t>(cache) << 32) | sNextTraceId++;
}
// From http://tools.ietf.org/html/draft-ietf-httpbis-p6-cache-21#section-6
// a "non-error response" is one with a 2xx (Successful) or 3xx
// (Redirection) status code.
bool NonErrorResponse(int status_code) {
int status_code_range = status_code / 100;
return status_code_range == 2 || status_code_range == 3;
}
bool IsOnBatteryPower() {
if (base::PowerMonitor::IsInitialized())
return base::PowerMonitor::IsOnBatteryPower();
return false;
}
enum ExternallyConditionalizedType {
EXTERNALLY_CONDITIONALIZED_CACHE_REQUIRES_VALIDATION,
EXTERNALLY_CONDITIONALIZED_CACHE_USABLE,
EXTERNALLY_CONDITIONALIZED_MISMATCHED_VALIDATORS,
EXTERNALLY_CONDITIONALIZED_MAX
};
// These values are persisted to logs. Entries should not be renumbered and
// numeric values should never be reused.
enum class RestrictedPrefetchReused {
kNotReused = 0,
kReused = 1,
kMaxValue = kReused
};
bool ShouldByPassCacheForFirstPartySets(
const absl::optional<int64_t>& clear_at_run_id,
const absl::optional<int64_t>& written_at_run_id) {
return clear_at_run_id.has_value() &&
(!written_at_run_id.has_value() ||
written_at_run_id.value() < clear_at_run_id.value());
}
} // namespace
#define CACHE_STATUS_HISTOGRAMS(type) \
UMA_HISTOGRAM_ENUMERATION("HttpCache.Pattern" type, cache_entry_status_, \
CacheEntryStatus::ENTRY_MAX)
#define IS_NO_STORE_HISTOGRAMS(type, is_no_store) \
base::UmaHistogramBoolean("HttpCache.IsNoStore" type, is_no_store)
struct HeaderNameAndValue {
const char* name;
const char* value;
};
// If the request includes one of these request headers, then avoid caching
// to avoid getting confused.
static const HeaderNameAndValue kPassThroughHeaders[] = {
{"if-unmodified-since", nullptr}, // causes unexpected 412s
{"if-match", nullptr}, // causes unexpected 412s
{"if-range", nullptr},
{nullptr, nullptr}};
struct ValidationHeaderInfo {
const char* request_header_name;
const char* related_response_header_name;
};
static const ValidationHeaderInfo kValidationHeaders[] = {
{ "if-modified-since", "last-modified" },
{ "if-none-match", "etag" },
};
// If the request includes one of these request headers, then avoid reusing
// our cached copy if any.
static const HeaderNameAndValue kForceFetchHeaders[] = {
{"cache-control", "no-cache"},
{"pragma", "no-cache"},
{nullptr, nullptr}};
// If the request includes one of these request headers, then force our
// cached copy (if any) to be revalidated before reusing it.
static const HeaderNameAndValue kForceValidateHeaders[] = {
{"cache-control", "max-age=0"},
{nullptr, nullptr}};
static bool HeaderMatches(const HttpRequestHeaders& headers,
const HeaderNameAndValue* search) {
for (; search->name; ++search) {
std::string header_value;
if (!headers.GetHeader(search->name, &header_value))
continue;
if (!search->value)
return true;
HttpUtil::ValuesIterator v(header_value.begin(), header_value.end(), ',');
while (v.GetNext()) {
if (base::EqualsCaseInsensitiveASCII(v.value_piece(), search->value))
return true;
}
}
return false;
}
//-----------------------------------------------------------------------------
HttpCache::Transaction::Transaction(RequestPriority priority, HttpCache* cache)
: trace_id_(GetNextTraceId(cache)),
priority_(priority),
cache_(cache->GetWeakPtr()) {
static_assert(HttpCache::Transaction::kNumValidationHeaders ==
std::size(kValidationHeaders),
"invalid number of validation headers");
io_callback_ = base::BindRepeating(&Transaction::OnIOComplete,
weak_factory_.GetWeakPtr());
cache_io_callback_ = base::BindRepeating(&Transaction::OnCacheIOComplete,
weak_factory_.GetWeakPtr());
}
HttpCache::Transaction::~Transaction() {
TRACE_EVENT_END("net", perfetto::Track(trace_id_));
RecordHistograms();
// We may have to issue another IO, but we should never invoke the callback_
// after this point.
callback_.Reset();
if (cache_) {
if (entry_) {
DoneWithEntry(false /* entry_is_complete */);
} else if (cache_pending_) {
cache_->RemovePendingTransaction(this);
}
}
}
HttpCache::Transaction::Mode HttpCache::Transaction::mode() const {
return mode_;
}
LoadState HttpCache::Transaction::GetWriterLoadState() const {
const HttpTransaction* transaction = network_transaction();
if (transaction)
return transaction->GetLoadState();
if (entry_ || !request_)
return LOAD_STATE_IDLE;
return LOAD_STATE_WAITING_FOR_CACHE;
}
const NetLogWithSource& HttpCache::Transaction::net_log() const {
return net_log_;
}
int HttpCache::Transaction::Start(const HttpRequestInfo* request,
CompletionOnceCallback callback,
const NetLogWithSource& net_log) {
DCHECK(request);
DCHECK(request->IsConsistent());
DCHECK(!callback.is_null());
TRACE_EVENT_BEGIN("net", "HttpCacheTransaction", perfetto::Track(trace_id_),
"url", request->url.spec());
// Ensure that we only have one asynchronous call at a time.
DCHECK(callback_.is_null());
DCHECK(!reading_);
DCHECK(!network_trans_.get());
DCHECK(!entry_);
DCHECK_EQ(next_state_, STATE_NONE);
if (!cache_.get())
return ERR_UNEXPECTED;
initial_request_ = request;
SetRequest(net_log);
// We have to wait until the backend is initialized so we start the SM.
next_state_ = STATE_GET_BACKEND;
int rv = DoLoop(OK);
// Setting this here allows us to check for the existence of a callback_ to
// determine if we are still inside Start.
if (rv == ERR_IO_PENDING)
callback_ = std::move(callback);
return rv;
}
int HttpCache::Transaction::RestartIgnoringLastError(
CompletionOnceCallback callback) {
DCHECK(!callback.is_null());
// Ensure that we only have one asynchronous call at a time.
DCHECK(callback_.is_null());
if (!cache_.get())
return ERR_UNEXPECTED;
int rv = RestartNetworkRequest();
if (rv == ERR_IO_PENDING)
callback_ = std::move(callback);
return rv;
}
int HttpCache::Transaction::RestartWithCertificate(
scoped_refptr<X509Certificate> client_cert,
scoped_refptr<SSLPrivateKey> client_private_key,
CompletionOnceCallback callback) {
DCHECK(!callback.is_null());
// Ensure that we only have one asynchronous call at a time.
DCHECK(callback_.is_null());
if (!cache_.get())
return ERR_UNEXPECTED;
int rv = RestartNetworkRequestWithCertificate(std::move(client_cert),
std::move(client_private_key));
if (rv == ERR_IO_PENDING)
callback_ = std::move(callback);
return rv;
}
int HttpCache::Transaction::RestartWithAuth(const AuthCredentials& credentials,
CompletionOnceCallback callback) {
DCHECK(auth_response_.headers.get());
DCHECK(!callback.is_null());
// Ensure that we only have one asynchronous call at a time.
DCHECK(callback_.is_null());
if (!cache_.get())
return ERR_UNEXPECTED;
// Clear the intermediate response since we are going to start over.
SetAuthResponse(HttpResponseInfo());
int rv = RestartNetworkRequestWithAuth(credentials);
if (rv == ERR_IO_PENDING)
callback_ = std::move(callback);
return rv;
}
bool HttpCache::Transaction::IsReadyToRestartForAuth() {
if (!network_trans_.get())
return false;
return network_trans_->IsReadyToRestartForAuth();
}
int HttpCache::Transaction::Read(IOBuffer* buf,
int buf_len,
CompletionOnceCallback callback) {
TRACE_EVENT_INSTANT("net", "HttpCacheTransaction::Read",
perfetto::Track(trace_id_), "buf_len", buf_len);
DCHECK_EQ(next_state_, STATE_NONE);
DCHECK(buf);
// TODO(https://crbug.com/1335423): Change to DCHECK_GT() or remove after bug
// is fixed.
CHECK_GT(buf_len, 0);
DCHECK(!callback.is_null());
DCHECK(callback_.is_null());
if (!cache_.get())
return ERR_UNEXPECTED;
// If we have an intermediate auth response at this point, then it means the
// user wishes to read the network response (the error page). If there is a
// previous response in the cache then we should leave it intact.
if (auth_response_.headers.get() && mode_ != NONE) {
UpdateCacheEntryStatus(CacheEntryStatus::ENTRY_OTHER);
DCHECK(mode_ & WRITE);
bool stopped = StopCachingImpl(mode_ == READ_WRITE);
DCHECK(stopped);
}
reading_ = true;
read_buf_ = buf;
read_buf_len_ = buf_len;
int rv = TransitionToReadingState();
if (rv != OK || next_state_ == STATE_NONE)
return rv;
rv = DoLoop(OK);
if (rv == ERR_IO_PENDING) {
DCHECK(callback_.is_null());
callback_ = std::move(callback);
}
return rv;
}
int HttpCache::Transaction::TransitionToReadingState() {
if (!entry_) {
if (network_trans_) {
// This can happen when the request should be handled exclusively by
// the network layer (skipping the cache entirely using
// LOAD_DISABLE_CACHE) or there was an error during the headers phase
// due to which the transaction cannot write to the cache or the consumer
// is reading the auth response from the network.
// TODO(http://crbug.com/740947) to get rid of this state in future.
next_state_ = STATE_NETWORK_READ;
return OK;
}
// If there is no network, and no cache entry, then there is nothing to read
// from.
next_state_ = STATE_NONE;
// An error state should be set for the next read, else this transaction
// should have been terminated once it reached this state. To assert we
// could dcheck that shared_writing_error_ is set to a valid error value but
// in some specific conditions (http://crbug.com/806344) it's possible that
// the consumer does an extra Read in which case the assert will fail.
return shared_writing_error_;
}
// If entry_ is present, the transaction is either a member of entry_->writers
// or readers.
if (!InWriters()) {
// Since transaction is not a writer and we are in Read(), it must be a
// reader.
DCHECK(entry_->TransactionInReaders(this));
DCHECK(mode_ == READ || (mode_ == READ_WRITE && partial_));
next_state_ = STATE_CACHE_READ_DATA;
return OK;
}
DCHECK(mode_ & WRITE || mode_ == NONE);
// If it's a writer and it is partial then it may need to read from the cache
// or from the network based on whether network transaction is present or not.
if (partial_) {
if (entry_->writers->network_transaction())
next_state_ = STATE_NETWORK_READ_CACHE_WRITE;
else
next_state_ = STATE_CACHE_READ_DATA;
return OK;
}
// Full request.
// If it's a writer and a full request then it may read from the cache if its
// offset is behind the current offset else from the network.
int disk_entry_size = entry_->GetEntry()->GetDataSize(kResponseContentIndex);
if (read_offset_ == disk_entry_size || entry_->writers->network_read_only()) {
next_state_ = STATE_NETWORK_READ_CACHE_WRITE;
} else {
DCHECK_LT(read_offset_, disk_entry_size);
next_state_ = STATE_CACHE_READ_DATA;
}
return OK;
}
void HttpCache::Transaction::StopCaching() {
// We really don't know where we are now. Hopefully there is no operation in
// progress, but nothing really prevents this method to be called after we
// returned ERR_IO_PENDING. We cannot attempt to truncate the entry at this
// point because we need the state machine for that (and even if we are really
// free, that would be an asynchronous operation). In other words, keep the
// entry how it is (it will be marked as truncated at destruction), and let
// the next piece of code that executes know that we are now reading directly
// from the net.
if (cache_.get() && (mode_ & WRITE) && !is_sparse_ && !range_requested_ &&
network_transaction()) {
StopCachingImpl(false);
}
}
int64_t HttpCache::Transaction::GetTotalReceivedBytes() const {
int64_t total_received_bytes = network_transaction_info_.total_received_bytes;
const HttpTransaction* transaction = GetOwnedOrMovedNetworkTransaction();
if (transaction)
total_received_bytes += transaction->GetTotalReceivedBytes();
return total_received_bytes;
}
int64_t HttpCache::Transaction::GetTotalSentBytes() const {
int64_t total_sent_bytes = network_transaction_info_.total_sent_bytes;
const HttpTransaction* transaction = GetOwnedOrMovedNetworkTransaction();
if (transaction)
total_sent_bytes += transaction->GetTotalSentBytes();
return total_sent_bytes;
}
void HttpCache::Transaction::DoneReading() {
if (cache_.get() && entry_) {
DCHECK_NE(mode_, UPDATE);
DoneWithEntry(true);
}
}
const HttpResponseInfo* HttpCache::Transaction::GetResponseInfo() const {
// Null headers means we encountered an error or haven't a response yet
if (auth_response_.headers.get()) {
DCHECK_EQ(cache_entry_status_, auth_response_.cache_entry_status)
<< "These must be in sync via SetResponse and SetAuthResponse.";
return &auth_response_;
}
// TODO(https://crbug.com/1219402): This should check in `response_`
return &response_;
}
LoadState HttpCache::Transaction::GetLoadState() const {
// If there's no pending callback, the ball is not in the
// HttpCache::Transaction's court, whatever else may be going on.
if (!callback_)
return LOAD_STATE_IDLE;
LoadState state = GetWriterLoadState();
if (state != LOAD_STATE_WAITING_FOR_CACHE)
return state;
if (cache_.get())
return cache_->GetLoadStateForPendingTransaction(this);
return LOAD_STATE_IDLE;
}
void HttpCache::Transaction::SetQuicServerInfo(
QuicServerInfo* quic_server_info) {}
bool HttpCache::Transaction::GetLoadTimingInfo(
LoadTimingInfo* load_timing_info) const {
const HttpTransaction* transaction = GetOwnedOrMovedNetworkTransaction();
if (transaction)
return transaction->GetLoadTimingInfo(load_timing_info);
if (network_transaction_info_.old_network_trans_load_timing) {
*load_timing_info =
*network_transaction_info_.old_network_trans_load_timing;
return true;
}
if (first_cache_access_since_.is_null())
return false;
// If the cache entry was opened, return that time.
load_timing_info->send_start = first_cache_access_since_;
// This time doesn't make much sense when reading from the cache, so just use
// the same time as send_start.
load_timing_info->send_end = first_cache_access_since_;
// Provide the time immediately before parsing a cached entry.
load_timing_info->receive_headers_start = read_headers_since_;
return true;
}
bool HttpCache::Transaction::GetRemoteEndpoint(IPEndPoint* endpoint) const {
const HttpTransaction* transaction = GetOwnedOrMovedNetworkTransaction();
if (transaction)
return transaction->GetRemoteEndpoint(endpoint);
if (!network_transaction_info_.old_remote_endpoint.address().empty()) {
*endpoint = network_transaction_info_.old_remote_endpoint;
return true;
}
return false;
}
void HttpCache::Transaction::PopulateNetErrorDetails(
NetErrorDetails* details) const {
const HttpTransaction* transaction = GetOwnedOrMovedNetworkTransaction();
if (transaction)
return transaction->PopulateNetErrorDetails(details);
return;
}
void HttpCache::Transaction::SetPriority(RequestPriority priority) {
priority_ = priority;
if (network_trans_)
network_trans_->SetPriority(priority_);
if (InWriters()) {
DCHECK(!network_trans_ || partial_);
entry_->writers->UpdatePriority();
}
}
void HttpCache::Transaction::SetWebSocketHandshakeStreamCreateHelper(
WebSocketHandshakeStreamBase::CreateHelper* create_helper) {
websocket_handshake_stream_base_create_helper_ = create_helper;
// TODO(shivanisha). Since this function must be invoked before Start() as
// per the API header, a network transaction should not exist at that point.
HttpTransaction* transaction = network_transaction();
if (transaction)
transaction->SetWebSocketHandshakeStreamCreateHelper(create_helper);
}
void HttpCache::Transaction::SetBeforeNetworkStartCallback(
BeforeNetworkStartCallback callback) {
DCHECK(!network_trans_);
before_network_start_callback_ = std::move(callback);
}
void HttpCache::Transaction::SetConnectedCallback(
const ConnectedCallback& callback) {
DCHECK(!network_trans_);
connected_callback_ = callback;
}
void HttpCache::Transaction::SetRequestHeadersCallback(
RequestHeadersCallback callback) {
DCHECK(!network_trans_);
request_headers_callback_ = std::move(callback);
}
void HttpCache::Transaction::SetResponseHeadersCallback(
ResponseHeadersCallback callback) {
DCHECK(!network_trans_);
response_headers_callback_ = std::move(callback);
}
void HttpCache::Transaction::SetEarlyResponseHeadersCallback(
ResponseHeadersCallback callback) {
DCHECK(!network_trans_);
early_response_headers_callback_ = std::move(callback);
}
void HttpCache::Transaction::SetModifyRequestHeadersCallback(
base::RepeatingCallback<void(net::HttpRequestHeaders*)> callback) {
// This method should not be called for this class.
NOTREACHED();
}
void HttpCache::Transaction::SetIsSharedDictionaryReadAllowedCallback(
base::RepeatingCallback<bool()> callback) {
DCHECK(!network_trans_);
is_shared_dictionary_read_allowed_callback_ = std::move(callback);
}
int HttpCache::Transaction::ResumeNetworkStart() {
if (network_trans_)
return network_trans_->ResumeNetworkStart();
return ERR_UNEXPECTED;
}
ConnectionAttempts HttpCache::Transaction::GetConnectionAttempts() const {
ConnectionAttempts attempts;
const HttpTransaction* transaction = GetOwnedOrMovedNetworkTransaction();
if (transaction)
attempts = transaction->GetConnectionAttempts();
attempts.insert(attempts.begin(),
network_transaction_info_.old_connection_attempts.begin(),
network_transaction_info_.old_connection_attempts.end());
return attempts;
}
void HttpCache::Transaction::CloseConnectionOnDestruction() {
if (network_trans_) {
network_trans_->CloseConnectionOnDestruction();
} else if (InWriters()) {
entry_->writers->CloseConnectionOnDestruction();
}
}
void HttpCache::Transaction::SetValidatingCannotProceed() {
DCHECK(!reading_);
// Ensure this transaction is waiting for a callback.
DCHECK_NE(STATE_UNSET, next_state_);
next_state_ = STATE_HEADERS_PHASE_CANNOT_PROCEED;
entry_ = nullptr;
}
void HttpCache::Transaction::WriterAboutToBeRemovedFromEntry(int result) {
TRACE_EVENT_INSTANT("net",
"HttpCacheTransaction::WriterAboutToBeRemovedFromEntry",
perfetto::Track(trace_id_));
// Since the transaction can no longer access the network transaction, save
// all network related info now.
if (moved_network_transaction_to_writers_ &&
entry_->writers->network_transaction()) {
SaveNetworkTransactionInfo(*(entry_->writers->network_transaction()));
}
entry_ = nullptr;
mode_ = NONE;
// Transactions in the midst of a Read call through writers will get any error
// code through the IO callback but for idle transactions/transactions reading
// from the cache, the error for a future Read must be stored here.
if (result < 0)
shared_writing_error_ = result;
}
void HttpCache::Transaction::WriteModeTransactionAboutToBecomeReader() {
TRACE_EVENT_INSTANT(
"net", "HttpCacheTransaction::WriteModeTransactionAboutToBecomeReader",
perfetto::Track(trace_id_));
mode_ = READ;
if (moved_network_transaction_to_writers_ &&
entry_->writers->network_transaction()) {
SaveNetworkTransactionInfo(*(entry_->writers->network_transaction()));
}
}
void HttpCache::Transaction::AddDiskCacheWriteTime(base::TimeDelta elapsed) {
total_disk_cache_write_time_ += elapsed;
}
//-----------------------------------------------------------------------------
// A few common patterns: (Foo* means Foo -> FooComplete)
//
// 1. Not-cached entry:
// Start():
// GetBackend* -> InitEntry -> OpenOrCreateEntry* -> AddToEntry* ->
// SendRequest* -> SuccessfulSendRequest -> OverwriteCachedResponse ->
// CacheWriteResponse* -> TruncateCachedData* -> PartialHeadersReceived ->
// FinishHeaders*
//
// Read():
// NetworkReadCacheWrite*/CacheReadData* (if other writers are also writing to
// the cache)
//
// 2. Cached entry, no validation:
// Start():
// GetBackend* -> InitEntry -> OpenOrCreateEntry* -> AddToEntry* ->
// CacheReadResponse* -> CacheDispatchValidation ->
// BeginPartialCacheValidation() -> BeginCacheValidation() ->
// ConnectedCallback* -> SetupEntryForRead() -> FinishHeaders*
//
// Read():
// CacheReadData*
//
// 3. Cached entry, validation (304):
// Start():
// GetBackend* -> InitEntry -> OpenOrCreateEntry* -> AddToEntry* ->
// CacheReadResponse* -> CacheDispatchValidation ->
// BeginPartialCacheValidation() -> BeginCacheValidation() -> SendRequest* ->
// SuccessfulSendRequest -> UpdateCachedResponse -> CacheWriteUpdatedResponse*
// -> UpdateCachedResponseComplete -> OverwriteCachedResponse ->
// PartialHeadersReceived -> FinishHeaders*
//
// Read():
// CacheReadData*
//
// 4. Cached entry, validation and replace (200):
// Start():
// GetBackend* -> InitEntry -> OpenOrCreateEntry* -> AddToEntry* ->
// CacheReadResponse* -> CacheDispatchValidation ->
// BeginPartialCacheValidation() -> BeginCacheValidation() -> SendRequest* ->
// SuccessfulSendRequest -> OverwriteCachedResponse -> CacheWriteResponse* ->
// DoTruncateCachedData* -> PartialHeadersReceived -> FinishHeaders*
//
// Read():
// NetworkReadCacheWrite*/CacheReadData* (if other writers are also writing to
// the cache)
//
// 5. Sparse entry, partially cached, byte range request:
// Start():
// GetBackend* -> InitEntry -> OpenOrCreateEntry* -> AddToEntry* ->
// CacheReadResponse* -> CacheDispatchValidation ->
// BeginPartialCacheValidation() -> CacheQueryData* ->
// ValidateEntryHeadersAndContinue() -> StartPartialCacheValidation ->
// CompletePartialCacheValidation -> BeginCacheValidation() -> SendRequest* ->
// SuccessfulSendRequest -> UpdateCachedResponse -> CacheWriteUpdatedResponse*
// -> UpdateCachedResponseComplete -> OverwriteCachedResponse ->
// PartialHeadersReceived -> FinishHeaders*
//
// Read() 1:
// NetworkReadCacheWrite*
//
// Read() 2:
// NetworkReadCacheWrite* -> StartPartialCacheValidation ->
// CompletePartialCacheValidation -> ConnectedCallback* -> CacheReadData*
//
// Read() 3:
// CacheReadData* -> StartPartialCacheValidation ->
// CompletePartialCacheValidation -> BeginCacheValidation() -> SendRequest* ->
// SuccessfulSendRequest -> UpdateCachedResponse* -> OverwriteCachedResponse
// -> PartialHeadersReceived -> NetworkReadCacheWrite*
//
// 6. HEAD. Not-cached entry:
// Pass through. Don't save a HEAD by itself.
// Start():
// GetBackend* -> InitEntry -> OpenOrCreateEntry* -> SendRequest*
//
// 7. HEAD. Cached entry, no validation:
// Start():
// The same flow as for a GET request (example #2)
//
// Read():
// CacheReadData (returns 0)
//
// 8. HEAD. Cached entry, validation (304):
// The request updates the stored headers.
// Start(): Same as for a GET request (example #3)
//
// Read():
// CacheReadData (returns 0)
//
// 9. HEAD. Cached entry, validation and replace (200):
// Pass through. The request dooms the old entry, as a HEAD won't be stored by
// itself.
// Start():
// GetBackend* -> InitEntry -> OpenOrCreateEntry* -> AddToEntry* ->
// CacheReadResponse* -> CacheDispatchValidation ->
// BeginPartialCacheValidation() -> BeginCacheValidation() -> SendRequest* ->
// SuccessfulSendRequest -> OverwriteCachedResponse -> FinishHeaders*
//
// 10. HEAD. Sparse entry, partially cached:
// Serve the request from the cache, as long as it doesn't require
// revalidation. Ignore missing ranges when deciding to revalidate. If the
// entry requires revalidation, ignore the whole request and go to full pass
// through (the result of the HEAD request will NOT update the entry).
//
// Start(): Basically the same as example 7, as we never create a partial_
// object for this request.
//
// 11. Prefetch, not-cached entry:
// The same as example 1. The "unused_since_prefetch" bit is stored as true in
// UpdateCachedResponse.
//
// 12. Prefetch, cached entry:
// Like examples 2-4, only CacheWriteUpdatedPrefetchResponse* is inserted
// between CacheReadResponse* and CacheDispatchValidation if the
// unused_since_prefetch bit is unset.
//
// 13. Cached entry less than 5 minutes old, unused_since_prefetch is true:
// Skip validation, similar to example 2.
// GetBackend* -> InitEntry -> OpenOrCreateEntry* -> AddToEntry* ->
// CacheReadResponse* -> CacheToggleUnusedSincePrefetch* ->
// CacheDispatchValidation -> BeginPartialCacheValidation() ->
// BeginCacheValidation() -> ConnectedCallback* -> SetupEntryForRead() ->
// FinishHeaders*
//
// Read():
// CacheReadData*
//
// 14. Cached entry more than 5 minutes old, unused_since_prefetch is true:
// Like examples 2-4, only CacheToggleUnusedSincePrefetch* is inserted between
// CacheReadResponse* and CacheDispatchValidation.
int HttpCache::Transaction::DoLoop(int result) {
DCHECK_NE(STATE_UNSET, next_state_);
DCHECK_NE(STATE_NONE, next_state_);
DCHECK(!in_do_loop_);
int rv = result;
State state = next_state_;
do {
state = next_state_;
next_state_ = STATE_UNSET;
base::AutoReset<bool> scoped_in_do_loop(&in_do_loop_, true);
switch (state) {
case STATE_GET_BACKEND:
DCHECK_EQ(OK, rv);
rv = DoGetBackend();
break;
case STATE_GET_BACKEND_COMPLETE:
rv = DoGetBackendComplete(rv);
break;
case STATE_INIT_ENTRY:
DCHECK_EQ(OK, rv);
rv = DoInitEntry();
break;
case STATE_OPEN_OR_CREATE_ENTRY:
DCHECK_EQ(OK, rv);
rv = DoOpenOrCreateEntry();
break;
case STATE_OPEN_OR_CREATE_ENTRY_COMPLETE:
rv = DoOpenOrCreateEntryComplete(rv);
break;
case STATE_DOOM_ENTRY:
DCHECK_EQ(OK, rv);
rv = DoDoomEntry();
break;
case STATE_DOOM_ENTRY_COMPLETE:
rv = DoDoomEntryComplete(rv);
break;
case STATE_CREATE_ENTRY:
DCHECK_EQ(OK, rv);
rv = DoCreateEntry();
break;
case STATE_CREATE_ENTRY_COMPLETE:
rv = DoCreateEntryComplete(rv);
break;
case STATE_ADD_TO_ENTRY:
DCHECK_EQ(OK, rv);
rv = DoAddToEntry();
break;
case STATE_ADD_TO_ENTRY_COMPLETE:
rv = DoAddToEntryComplete(rv);
break;
case STATE_DONE_HEADERS_ADD_TO_ENTRY_COMPLETE:
rv = DoDoneHeadersAddToEntryComplete(rv);
break;
case STATE_CACHE_READ_RESPONSE:
DCHECK_EQ(OK, rv);
rv = DoCacheReadResponse();
break;
case STATE_CACHE_READ_RESPONSE_COMPLETE:
rv = DoCacheReadResponseComplete(rv);
break;
case STATE_WRITE_UPDATED_PREFETCH_RESPONSE:
DCHECK_EQ(OK, rv);
rv = DoCacheWriteUpdatedPrefetchResponse(rv);
break;
case STATE_WRITE_UPDATED_PREFETCH_RESPONSE_COMPLETE:
rv = DoCacheWriteUpdatedPrefetchResponseComplete(rv);
break;
case STATE_CACHE_DISPATCH_VALIDATION:
DCHECK_EQ(OK, rv);
rv = DoCacheDispatchValidation();
break;
case STATE_CACHE_QUERY_DATA:
DCHECK_EQ(OK, rv);
rv = DoCacheQueryData();
break;
case STATE_CACHE_QUERY_DATA_COMPLETE:
rv = DoCacheQueryDataComplete(rv);
break;
case STATE_START_PARTIAL_CACHE_VALIDATION:
DCHECK_EQ(OK, rv);
rv = DoStartPartialCacheValidation();
break;
case STATE_COMPLETE_PARTIAL_CACHE_VALIDATION:
rv = DoCompletePartialCacheValidation(rv);
break;
case STATE_CACHE_UPDATE_STALE_WHILE_REVALIDATE_TIMEOUT:
DCHECK_EQ(OK, rv);
rv = DoCacheUpdateStaleWhileRevalidateTimeout();
break;
case STATE_CACHE_UPDATE_STALE_WHILE_REVALIDATE_TIMEOUT_COMPLETE:
rv = DoCacheUpdateStaleWhileRevalidateTimeoutComplete(rv);
break;
case STATE_CONNECTED_CALLBACK:
rv = DoConnectedCallback();
break;
case STATE_CONNECTED_CALLBACK_COMPLETE:
rv = DoConnectedCallbackComplete(rv);
break;
case STATE_SETUP_ENTRY_FOR_READ:
DCHECK_EQ(OK, rv);
rv = DoSetupEntryForRead();
break;
case STATE_SEND_REQUEST:
DCHECK_EQ(OK, rv);
rv = DoSendRequest();
break;
case STATE_SEND_REQUEST_COMPLETE:
rv = DoSendRequestComplete(rv);
break;
case STATE_SUCCESSFUL_SEND_REQUEST:
DCHECK_EQ(OK, rv);
rv = DoSuccessfulSendRequest();
break;
case STATE_UPDATE_CACHED_RESPONSE:
DCHECK_EQ(OK, rv);
rv = DoUpdateCachedResponse();
break;
case STATE_CACHE_WRITE_UPDATED_RESPONSE:
DCHECK_EQ(OK, rv);
rv = DoCacheWriteUpdatedResponse();
break;
case STATE_CACHE_WRITE_UPDATED_RESPONSE_COMPLETE:
rv = DoCacheWriteUpdatedResponseComplete(rv);
break;
case STATE_UPDATE_CACHED_RESPONSE_COMPLETE:
rv = DoUpdateCachedResponseComplete(rv);
break;
case STATE_OVERWRITE_CACHED_RESPONSE:
DCHECK_EQ(OK, rv);
rv = DoOverwriteCachedResponse();
break;
case STATE_CACHE_WRITE_RESPONSE:
DCHECK_EQ(OK, rv);
rv = DoCacheWriteResponse();
break;
case STATE_CACHE_WRITE_RESPONSE_COMPLETE:
rv = DoCacheWriteResponseComplete(rv);
break;
case STATE_TRUNCATE_CACHED_DATA:
DCHECK_EQ(OK, rv);
rv = DoTruncateCachedData();
break;
case STATE_TRUNCATE_CACHED_DATA_COMPLETE:
rv = DoTruncateCachedDataComplete(rv);
break;
case STATE_PARTIAL_HEADERS_RECEIVED:
DCHECK_EQ(OK, rv);
rv = DoPartialHeadersReceived();
break;
case STATE_HEADERS_PHASE_CANNOT_PROCEED:
rv = DoHeadersPhaseCannotProceed(rv);
break;
case STATE_FINISH_HEADERS:
rv = DoFinishHeaders(rv);
break;
case STATE_FINISH_HEADERS_COMPLETE:
rv = DoFinishHeadersComplete(rv);
break;
case STATE_NETWORK_READ_CACHE_WRITE:
DCHECK_EQ(OK, rv);
rv = DoNetworkReadCacheWrite();
break;
case STATE_NETWORK_READ_CACHE_WRITE_COMPLETE:
rv = DoNetworkReadCacheWriteComplete(rv);
break;
case STATE_CACHE_READ_DATA:
DCHECK_EQ(OK, rv);
rv = DoCacheReadData();
break;
case STATE_CACHE_READ_DATA_COMPLETE:
rv = DoCacheReadDataComplete(rv);
break;
case STATE_NETWORK_READ:
DCHECK_EQ(OK, rv);
rv = DoNetworkRead();
break;
case STATE_NETWORK_READ_COMPLETE:
rv = DoNetworkReadComplete(rv);
break;
default:
NOTREACHED() << "bad state " << state;