-
Notifications
You must be signed in to change notification settings - Fork 128
/
Copy pathquic_stream_factory.cc
2703 lines (2393 loc) · 101 KB
/
quic_stream_factory.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/quic/quic_stream_factory.h"
#include <memory>
#include <set>
#include <tuple>
#include <utility>
#include "base/containers/contains.h"
#include "base/feature_list.h"
#include "base/functional/bind.h"
#include "base/location.h"
#include "base/memory/memory_pressure_monitor.h"
#include "base/memory/raw_ptr.h"
#include "base/memory/raw_ptr_exclusion.h"
#include "base/metrics/field_trial.h"
#include "base/metrics/histogram_functions.h"
#include "base/metrics/histogram_macros.h"
#include "base/no_destructor.h"
#include "base/numerics/safe_conversions.h"
#include "base/ranges/algorithm.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/task/sequenced_task_runner.h"
#include "base/task/single_thread_task_runner.h"
#include "base/time/default_clock.h"
#include "base/time/default_tick_clock.h"
#include "base/values.h"
#include "crypto/openssl_util.h"
#include "net/base/address_list.h"
#include "net/base/features.h"
#include "net/base/ip_address.h"
#include "net/base/net_errors.h"
#include "net/base/trace_constants.h"
#include "net/base/tracing.h"
#include "net/cert/cert_verifier.h"
#include "net/dns/host_resolver.h"
#include "net/dns/public/secure_dns_policy.h"
#include "net/log/net_log.h"
#include "net/log/net_log_capture_mode.h"
#include "net/log/net_log_event_type.h"
#include "net/log/net_log_source_type.h"
#include "net/quic/address_utils.h"
#include "net/quic/crypto/proof_verifier_chromium.h"
#include "net/quic/properties_based_quic_server_info.h"
#include "net/quic/quic_chromium_alarm_factory.h"
#include "net/quic/quic_chromium_connection_helper.h"
#include "net/quic/quic_chromium_packet_reader.h"
#include "net/quic/quic_chromium_packet_writer.h"
#include "net/quic/quic_context.h"
#include "net/quic/quic_crypto_client_stream_factory.h"
#include "net/quic/quic_http_stream.h"
#include "net/quic/quic_server_info.h"
#include "net/socket/client_socket_factory.h"
#include "net/socket/next_proto.h"
#include "net/socket/socket_performance_watcher.h"
#include "net/socket/socket_performance_watcher_factory.h"
#include "net/socket/udp_client_socket.h"
#include "net/ssl/cert_compression.h"
#include "net/ssl/ssl_key_logger.h"
#include "net/third_party/quiche/src/quiche/quic/core/crypto/null_decrypter.h"
#include "net/third_party/quiche/src/quiche/quic/core/crypto/proof_verifier.h"
#include "net/third_party/quiche/src/quiche/quic/core/crypto/quic_client_session_cache.h"
#include "net/third_party/quiche/src/quiche/quic/core/crypto/quic_random.h"
#include "net/third_party/quiche/src/quiche/quic/core/http/quic_client_promised_info.h"
#include "net/third_party/quiche/src/quiche/quic/core/http/quic_client_push_promise_index.h"
#include "net/third_party/quiche/src/quiche/quic/core/quic_clock.h"
#include "net/third_party/quiche/src/quiche/quic/core/quic_connection.h"
#include "net/third_party/quiche/src/quiche/quic/core/quic_utils.h"
#include "net/third_party/quiche/src/quiche/quic/platform/api/quic_flags.h"
#include "third_party/boringssl/src/include/openssl/aead.h"
#include "url/gurl.h"
#include "url/scheme_host_port.h"
#include "url/url_constants.h"
namespace net {
namespace {
enum InitialRttEstimateSource {
INITIAL_RTT_DEFAULT,
INITIAL_RTT_CACHED,
INITIAL_RTT_2G,
INITIAL_RTT_3G,
INITIAL_RTT_SOURCE_MAX,
};
// These values are logged to UMA. Entries should not be renumbered and
// numeric values should never be reused. Please keep in sync with
// "ConnectionStateAfterDNS" in src/tools/metrics/histograms/enums.xml.
enum class ConnectionStateAfterDNS {
kDNSFailed = 0,
kIpPooled = 1,
kWaitingForCryptoDnsMatched = 2,
kWaitingForCryptoDnsNoMatch = 3,
kCryptoFinishedDnsMatch = 4,
kCryptoFinishedDnsNoMatch = 5,
kMaxValue = kCryptoFinishedDnsNoMatch,
};
enum class JobProtocolErrorLocation {
kSessionStartReadingFailedAsync = 0,
kSessionStartReadingFailedSync = 1,
kCreateSessionFailedAsync = 2,
kCreateSessionFailedSync = 3,
kCryptoConnectFailedSync = 4,
kCryptoConnectFailedAsync = 5,
kMaxValue = kCryptoConnectFailedAsync,
};
base::Value::Dict NetLogQuicStreamFactoryJobParams(
const QuicStreamFactory::QuicSessionAliasKey* key) {
base::Value::Dict dict;
dict.Set("host", key->server_id().host());
dict.Set("port", key->server_id().port());
dict.Set("privacy_mode",
PrivacyModeToDebugString(key->session_key().privacy_mode()));
dict.Set("network_anonymization_key",
key->session_key().network_anonymization_key().ToDebugString());
return dict;
}
std::string QuicPlatformNotificationToString(
QuicPlatformNotification notification) {
switch (notification) {
case NETWORK_CONNECTED:
return "OnNetworkConnected";
case NETWORK_MADE_DEFAULT:
return "OnNetworkMadeDefault";
case NETWORK_DISCONNECTED:
return "OnNetworkDisconnected";
case NETWORK_SOON_TO_DISCONNECT:
return "OnNetworkSoonToDisconnect";
case NETWORK_IP_ADDRESS_CHANGED:
return "OnIPAddressChanged";
default:
QUICHE_NOTREACHED();
break;
}
return "InvalidNotification";
}
void HistogramCreateSessionFailure(enum CreateSessionFailure error) {
UMA_HISTOGRAM_ENUMERATION("Net.QuicSession.CreationError", error,
CREATION_ERROR_MAX);
}
void HistogramProtocolErrorLocation(enum JobProtocolErrorLocation location) {
UMA_HISTOGRAM_ENUMERATION("Net.QuicStreamFactory.DoConnectFailureLocation",
location);
}
void LogConnectionIpPooling(bool pooled) {
UMA_HISTOGRAM_BOOLEAN("Net.QuicSession.ConnectionIpPooled", pooled);
}
void LogRacingStatus(ConnectionStateAfterDNS status) {
UMA_HISTOGRAM_ENUMERATION("Net.QuicSession.ConnectionStateAfterDNS", status);
}
void LogStaleConnectionTime(base::TimeTicks start_time) {
UMA_HISTOGRAM_TIMES("Net.QuicSession.StaleConnectionTime",
base::TimeTicks::Now() - start_time);
}
void LogValidConnectionTime(base::TimeTicks start_time) {
UMA_HISTOGRAM_TIMES("Net.QuicSession.ValidConnectionTime",
base::TimeTicks::Now() - start_time);
}
void LogFreshDnsResolveTime(base::TimeTicks start_time) {
UMA_HISTOGRAM_TIMES("Net.QuicSession.FreshDnsResolutionTime",
base::TimeTicks::Now() - start_time);
}
void SetInitialRttEstimate(base::TimeDelta estimate,
enum InitialRttEstimateSource source,
quic::QuicConfig* config) {
UMA_HISTOGRAM_ENUMERATION("Net.QuicSession.InitialRttEsitmateSource", source,
INITIAL_RTT_SOURCE_MAX);
if (estimate != base::TimeDelta())
config->SetInitialRoundTripTimeUsToSend(
base::checked_cast<uint64_t>(estimate.InMicroseconds()));
}
// An implementation of quic::QuicCryptoClientConfig::ServerIdFilter that wraps
// an |origin_filter|.
class ServerIdOriginFilter
: public quic::QuicCryptoClientConfig::ServerIdFilter {
public:
explicit ServerIdOriginFilter(
const base::RepeatingCallback<bool(const GURL&)> origin_filter)
: origin_filter_(origin_filter) {}
bool Matches(const quic::QuicServerId& server_id) const override {
if (origin_filter_.is_null())
return true;
GURL url(base::StringPrintf("%s%s%s:%d", url::kHttpsScheme,
url::kStandardSchemeSeparator,
server_id.host().c_str(), server_id.port()));
DCHECK(url.is_valid());
return origin_filter_.Run(url);
}
private:
const base::RepeatingCallback<bool(const GURL&)> origin_filter_;
};
std::set<std::string> HostsFromOrigins(std::set<HostPortPair> origins) {
std::set<std::string> hosts;
for (const auto& origin : origins) {
hosts.insert(origin.host());
}
return hosts;
}
} // namespace
// Refcounted class that owns quic::QuicCryptoClientConfig and tracks how many
// consumers are using it currently. When the last reference is freed, the
// QuicCryptoClientConfigHandle informs the owning QuicStreamFactory, moves it
// into an MRU cache.
class QuicStreamFactory::QuicCryptoClientConfigOwner {
public:
QuicCryptoClientConfigOwner(
std::unique_ptr<quic::ProofVerifier> proof_verifier,
std::unique_ptr<quic::QuicClientSessionCache> session_cache,
QuicStreamFactory* quic_stream_factory)
: config_(std::move(proof_verifier), std::move(session_cache)),
clock_(base::DefaultClock::GetInstance()),
quic_stream_factory_(quic_stream_factory) {
DCHECK(quic_stream_factory_);
memory_pressure_listener_ = std::make_unique<base::MemoryPressureListener>(
FROM_HERE,
base::BindRepeating(&QuicCryptoClientConfigOwner::OnMemoryPressure,
base::Unretained(this)));
}
QuicCryptoClientConfigOwner(const QuicCryptoClientConfigOwner&) = delete;
QuicCryptoClientConfigOwner& operator=(const QuicCryptoClientConfigOwner&) =
delete;
~QuicCryptoClientConfigOwner() { DCHECK_EQ(num_refs_, 0); }
quic::QuicCryptoClientConfig* config() { return &config_; }
int num_refs() const { return num_refs_; }
QuicStreamFactory* quic_stream_factory() { return quic_stream_factory_; }
void OnMemoryPressure(
base::MemoryPressureListener::MemoryPressureLevel memory_pressure_level) {
quic::SessionCache* session_cache = config_.mutable_session_cache();
if (!session_cache) {
return;
}
time_t now = clock_->Now().ToTimeT();
uint64_t now_u64 = 0;
if (now > 0) {
now_u64 = static_cast<uint64_t>(now);
}
switch (memory_pressure_level) {
case base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_NONE:
break;
case base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_MODERATE:
session_cache->RemoveExpiredEntries(
quic::QuicWallTime::FromUNIXSeconds(now_u64));
break;
case base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_CRITICAL:
session_cache->Clear();
break;
}
}
private:
friend class CryptoClientConfigHandle;
// Simple ref counting. Not using scoped_refptr allows for both keeping around
// an MRU cache of 0-reference objects, and DCHECKing that there are no
// outstanding referenced QuicCryptoClientConfigOwner on destruction. Private
// so that only CryptoClientConfigHandle can add and remove refs.
void AddRef() { num_refs_++; }
void ReleaseRef() {
DCHECK_GT(num_refs_, 0);
num_refs_--;
}
int num_refs_ = 0;
quic::QuicCryptoClientConfig config_;
raw_ptr<base::Clock> clock_;
std::unique_ptr<base::MemoryPressureListener> memory_pressure_listener_;
const raw_ptr<QuicStreamFactory> quic_stream_factory_;
};
// Class that owns a reference to a QuicCryptoClientConfigOwner. Handles
// incrementing the refcount on construction, and decrementing it on
// destruction.
class QuicStreamFactory::CryptoClientConfigHandle
: public QuicCryptoClientConfigHandle {
public:
explicit CryptoClientConfigHandle(
const QuicCryptoClientConfigMap::iterator& map_iterator)
: map_iterator_(map_iterator) {
DCHECK_GE(map_iterator_->second->num_refs(), 0);
map_iterator->second->AddRef();
}
CryptoClientConfigHandle(const CryptoClientConfigHandle& other)
: CryptoClientConfigHandle(other.map_iterator_) {}
CryptoClientConfigHandle& operator=(const CryptoClientConfigHandle&) = delete;
~CryptoClientConfigHandle() override {
DCHECK_GT(map_iterator_->second->num_refs(), 0);
map_iterator_->second->ReleaseRef();
if (map_iterator_->second->num_refs() == 0) {
map_iterator_->second->quic_stream_factory()
->OnAllCryptoClientRefReleased(map_iterator_);
}
}
quic::QuicCryptoClientConfig* GetConfig() const override {
return map_iterator_->second->config();
}
private:
QuicCryptoClientConfigMap::iterator map_iterator_;
};
// Responsible for creating a new QUIC session to the specified server, and
// for notifying any associated requests when complete. |client_config_handle|
// is not actually used, but serves to keep the corresponding CryptoClientConfig
// alive until the Job completes.
class QuicStreamFactory::Job {
public:
Job(QuicStreamFactory* factory,
quic::ParsedQuicVersion quic_version,
HostResolver* host_resolver,
const QuicSessionAliasKey& key,
std::unique_ptr<CryptoClientConfigHandle> client_config_handle,
bool was_alternative_service_recently_broken,
bool retry_on_alternate_network_before_handshake,
bool race_stale_dns_on_connection,
RequestPriority priority,
bool use_dns_aliases,
bool require_dns_https_alpn,
int cert_verify_flags,
const NetLogWithSource& net_log);
Job(const Job&) = delete;
Job& operator=(const Job&) = delete;
~Job();
int Run(CompletionOnceCallback callback);
int DoLoop(int rv);
int DoResolveHost();
int DoResolveHostComplete(int rv);
int DoCreateSession();
int DoCreateSessionComplete(int rv);
int DoConnect(int rv);
int DoConnectComplete(int rv);
int DoConfirmConnection(int rv);
int DoValidateHost();
void OnCreateSessionComplete(int rv);
void MaybeOnQuicSessionCreationComplete(int rv);
void OnResolveHostComplete(int rv);
void OnCryptoConnectComplete(int rv);
void OnSessionClosed(QuicChromiumClientSession* session);
const QuicSessionAliasKey& key() const { return key_; }
const NetLogWithSource& net_log() const { return net_log_; }
base::WeakPtr<Job> GetWeakPtr() { return weak_factory_.GetWeakPtr(); }
void PopulateNetErrorDetails(NetErrorDetails* details) const;
void AddRequest(QuicStreamRequest* request) {
stream_requests_.insert(request);
if (!host_resolution_finished_) {
request->ExpectOnHostResolution();
}
// Callers do not need to wait for OnQuicSessionCreationComplete if the
// kAsyncQuicSession flag is not set because session creation will be fully
// synchronous, so no need to call ExpectQuicSessionCreation.
if (base::FeatureList::IsEnabled(net::features::kAsyncQuicSession)) {
request->ExpectQuicSessionCreation();
}
}
void RemoveRequest(QuicStreamRequest* request) {
auto request_iter = stream_requests_.find(request);
DCHECK(request_iter != stream_requests_.end());
stream_requests_.erase(request_iter);
}
void SetPriority(RequestPriority priority) {
if (priority_ == priority)
return;
priority_ = priority;
if (resolve_host_request_ && !host_resolution_finished_) {
if (fresh_resolve_host_request_) {
fresh_resolve_host_request_->ChangeRequestPriority(priority);
} else {
resolve_host_request_->ChangeRequestPriority(priority);
}
}
}
const std::set<QuicStreamRequest*>& stream_requests() {
return stream_requests_;
}
RequestPriority priority() const { return priority_; }
private:
enum IoState {
STATE_NONE,
STATE_RESOLVE_HOST,
STATE_RESOLVE_HOST_COMPLETE,
STATE_CREATE_SESSION,
STATE_CREATE_SESSION_COMPLETE,
STATE_CONNECT,
STATE_CONNECT_COMPLETE,
STATE_HOST_VALIDATION,
STATE_CONFIRM_CONNECTION,
};
void CloseStaleHostConnection() {
DVLOG(1) << "Closing connection from stale host.";
if (session_) {
QuicChromiumClientSession* session = session_;
session_ = nullptr;
// Use ERR_FAILED instead of ERR_ABORTED out of paranoia - ERR_ABORTED
// should only be used when the next layer up cancels a request, and has
// special semantic meaning for some consumers when they see it.
session->CloseSessionOnErrorLater(
ERR_FAILED, quic::QUIC_STALE_CONNECTION_CANCELLED,
quic::ConnectionCloseBehavior::SEND_CONNECTION_CLOSE_PACKET);
}
}
bool DoesConnectionMatchFreshHostResolution() {
if (!session_)
return false;
DCHECK(quic_version_used_.IsKnown());
IPEndPoint stale_address = endpoint_result_.ip_endpoints.front();
bool svcb_optional =
IsSvcbOptional(*fresh_resolve_host_request_->GetEndpointResults());
for (const auto& candidate :
*fresh_resolve_host_request_->GetEndpointResults()) {
// TODO(https://crbug.com/1416963): Should other values also be checked
// for consistency?
if (SelectQuicVersion(candidate, svcb_optional) == quic_version_used_ &&
base::Contains(candidate.ip_endpoints, stale_address)) {
return true;
}
}
return false;
}
// Returns whether the client should be SVCB-optional when connecting to
// `results`.
bool IsSvcbOptional(
base::span<const HostResolverEndpointResult> results) const {
// If SVCB/HTTPS resolution succeeded, the client supports ECH, and all
// routes support ECH, disable the A/AAAA fallback. See Section 10.1 of
// draft-ietf-dnsop-svcb-https-11.
if (!factory_->ssl_config_service_->GetSSLContextConfig()
.EncryptedClientHelloEnabled() ||
!base::FeatureList::IsEnabled(features::kEncryptedClientHelloQuic)) {
return true; // ECH is not supported for this request.
}
return !HostResolver::AllProtocolEndpointsHaveEch(results);
}
// Returns the QUIC version that would be used with `endpoint_result`, or
// `quic::ParsedQuicVersion::Unsupported()` if `endpoint_result` cannot be
// used with QUIC.
quic::ParsedQuicVersion SelectQuicVersion(
const HostResolverEndpointResult& endpoint_result,
bool svcb_optional) const {
// TODO(davidben): `require_dns_https_alpn_` only exists to be `DCHECK`ed
// for consistency against `quic_version_`. Remove the parameter?
DCHECK_EQ(require_dns_https_alpn_, !quic_version_.IsKnown());
if (endpoint_result.metadata.supported_protocol_alpns.empty()) {
// `endpoint_result` came from A/AAAA records directly, without HTTPS/SVCB
// records. If we know the QUIC ALPN to use externally, i.e. via Alt-Svc,
// use it in SVCB-optional mode. Otherwise, `endpoint_result` is not
// eligible for QUIC.
return svcb_optional ? quic_version_
: quic::ParsedQuicVersion::Unsupported();
}
// Otherwise, `endpoint_result` came from an HTTPS/SVCB record. We can use
// QUIC if a suitable match is found in the record's ALPN list.
// Additionally, if this connection attempt came from Alt-Svc, the DNS
// result must be consistent with it. See
// https://www.ietf.org/archive/id/draft-ietf-dnsop-svcb-https-11.html#name-interaction-with-alt-svc
if (quic_version_.IsKnown()) {
std::string expected_alpn = quic::AlpnForVersion(quic_version_);
if (base::Contains(endpoint_result.metadata.supported_protocol_alpns,
quic::AlpnForVersion(quic_version_))) {
return quic_version_;
}
return quic::ParsedQuicVersion::Unsupported();
}
for (const auto& alpn : endpoint_result.metadata.supported_protocol_alpns) {
for (const auto& supported_version : factory_->supported_versions()) {
if (alpn == AlpnForVersion(supported_version)) {
return supported_version;
}
}
}
return quic::ParsedQuicVersion::Unsupported();
}
void LogStaleHostRacing(bool used) {
if (used) {
net_log_.AddEvent(
NetLogEventType::
QUIC_STREAM_FACTORY_JOB_STALE_HOST_TRIED_ON_CONNECTION);
} else {
net_log_.AddEvent(
NetLogEventType::
QUIC_STREAM_FACTORY_JOB_STALE_HOST_NOT_USED_ON_CONNECTION);
}
UMA_HISTOGRAM_BOOLEAN("Net.QuicSession.StaleHostRacing", used);
}
void LogStaleAndFreshHostMatched(bool matched) {
if (matched) {
net_log_.AddEvent(
NetLogEventType::
QUIC_STREAM_FACTORY_JOB_STALE_HOST_RESOLUTION_MATCHED);
} else {
net_log_.AddEvent(
NetLogEventType::
QUIC_STREAM_FACTORY_JOB_STALE_HOST_RESOLUTION_NO_MATCH);
}
UMA_HISTOGRAM_BOOLEAN("Net.QuicSession.StaleAndFreshHostMatched", matched);
}
IoState io_state_ = STATE_RESOLVE_HOST;
raw_ptr<QuicStreamFactory> factory_;
quic::ParsedQuicVersion quic_version_;
quic::ParsedQuicVersion quic_version_used_ =
quic::ParsedQuicVersion::Unsupported();
raw_ptr<HostResolver> host_resolver_;
const QuicSessionAliasKey key_;
const std::unique_ptr<CryptoClientConfigHandle> client_config_handle_;
RequestPriority priority_;
const bool use_dns_aliases_;
const bool require_dns_https_alpn_;
const int cert_verify_flags_;
const bool was_alternative_service_recently_broken_;
const bool retry_on_alternate_network_before_handshake_;
const bool race_stale_dns_on_connection_;
const NetLogWithSource net_log_;
bool create_session_on_stale_dns_ = false;
bool host_resolution_finished_ = false;
bool quic_session_created_ = false;
bool connection_retried_ = false;
// This field is not a raw_ptr<> because it was filtered by the rewriter for:
// #addr-of
RAW_PTR_EXCLUSION QuicChromiumClientSession* session_ = nullptr;
HostResolverEndpointResult endpoint_result_;
// If connection migraiton is supported, |network_| denotes the network on
// which |session_| is created.
handles::NetworkHandle network_;
CompletionOnceCallback host_resolution_callback_;
CompletionOnceCallback callback_;
std::unique_ptr<HostResolver::ResolveHostRequest> resolve_host_request_;
// Only set during DNS race. After completion, cleared or replaces
// |resolve_host_request_|.
std::unique_ptr<HostResolver::ResolveHostRequest> fresh_resolve_host_request_;
base::TimeTicks dns_resolution_start_time_;
base::TimeTicks dns_resolution_end_time_;
base::TimeTicks quic_connection_start_time_;
std::set<QuicStreamRequest*> stream_requests_;
base::WeakPtrFactory<Job> weak_factory_{this};
};
QuicStreamFactory::Job::Job(
QuicStreamFactory* factory,
quic::ParsedQuicVersion quic_version,
HostResolver* host_resolver,
const QuicSessionAliasKey& key,
std::unique_ptr<CryptoClientConfigHandle> client_config_handle,
bool was_alternative_service_recently_broken,
bool retry_on_alternate_network_before_handshake,
bool race_stale_dns_on_connection,
RequestPriority priority,
bool use_dns_aliases,
bool require_dns_https_alpn,
int cert_verify_flags,
const NetLogWithSource& net_log)
: factory_(factory),
quic_version_(quic_version),
host_resolver_(host_resolver),
key_(key),
client_config_handle_(std::move(client_config_handle)),
priority_(priority),
use_dns_aliases_(use_dns_aliases),
require_dns_https_alpn_(require_dns_https_alpn),
cert_verify_flags_(cert_verify_flags),
was_alternative_service_recently_broken_(
was_alternative_service_recently_broken),
retry_on_alternate_network_before_handshake_(
retry_on_alternate_network_before_handshake),
race_stale_dns_on_connection_(race_stale_dns_on_connection),
net_log_(
NetLogWithSource::Make(net_log.net_log(),
NetLogSourceType::QUIC_STREAM_FACTORY_JOB)),
network_(handles::kInvalidNetworkHandle) {
DCHECK_EQ(quic_version.IsKnown(), !require_dns_https_alpn);
net_log_.BeginEvent(NetLogEventType::QUIC_STREAM_FACTORY_JOB,
[&] { return NetLogQuicStreamFactoryJobParams(&key_); });
// Associate |net_log_| with |net_log|.
net_log_.AddEventReferencingSource(
NetLogEventType::QUIC_STREAM_FACTORY_JOB_BOUND_TO_HTTP_STREAM_JOB,
net_log.source());
net_log.AddEventReferencingSource(
NetLogEventType::HTTP_STREAM_JOB_BOUND_TO_QUIC_STREAM_FACTORY_JOB,
net_log_.source());
}
QuicStreamFactory::Job::~Job() {
net_log_.EndEvent(NetLogEventType::QUIC_STREAM_FACTORY_JOB);
// If |this| is destroyed in QuicStreamFactory's destructor, |callback_| is
// non-null.
}
int QuicStreamFactory::Job::Run(CompletionOnceCallback callback) {
int rv = DoLoop(OK);
if (rv == ERR_IO_PENDING)
callback_ = std::move(callback);
return rv > 0 ? OK : rv;
}
int QuicStreamFactory::Job::DoLoop(int rv) {
TRACE_EVENT0(NetTracingCategory(), "QuicStreamFactory::Job::DoLoop");
do {
IoState state = io_state_;
io_state_ = STATE_NONE;
switch (state) {
case STATE_RESOLVE_HOST:
CHECK_EQ(OK, rv);
rv = DoResolveHost();
break;
case STATE_RESOLVE_HOST_COMPLETE:
rv = DoResolveHostComplete(rv);
break;
case STATE_CREATE_SESSION:
rv = DoCreateSession();
break;
case STATE_CREATE_SESSION_COMPLETE:
rv = DoCreateSessionComplete(rv);
break;
case STATE_CONNECT:
rv = DoConnect(rv);
break;
case STATE_CONNECT_COMPLETE:
rv = DoConnectComplete(rv);
break;
case STATE_HOST_VALIDATION:
rv = DoValidateHost();
break;
case STATE_CONFIRM_CONNECTION:
rv = DoConfirmConnection(rv);
break;
default:
NOTREACHED() << "io_state_: " << io_state_;
break;
}
} while (io_state_ != STATE_NONE && rv != ERR_IO_PENDING);
return rv;
}
void QuicStreamFactory::Job::OnSessionClosed(
QuicChromiumClientSession* session) {
// When dns racing experiment is on, the job needs to know that the stale
// session is closed so that it will start the fresh session without matching
// dns results.
if (io_state_ == STATE_HOST_VALIDATION && session_ == session) {
DCHECK(race_stale_dns_on_connection_);
DCHECK(fresh_resolve_host_request_);
resolve_host_request_ = std::move(fresh_resolve_host_request_);
session_ = nullptr;
io_state_ = STATE_RESOLVE_HOST_COMPLETE;
}
}
void QuicStreamFactory::Job::OnResolveHostComplete(int rv) {
DCHECK(!host_resolution_finished_);
LogFreshDnsResolveTime(dns_resolution_start_time_);
if (fresh_resolve_host_request_) {
DCHECK(race_stale_dns_on_connection_);
dns_resolution_end_time_ = base::TimeTicks::Now();
if (rv != OK) {
LogRacingStatus(ConnectionStateAfterDNS::kDNSFailed);
CloseStaleHostConnection();
resolve_host_request_ = std::move(fresh_resolve_host_request_);
io_state_ = STATE_RESOLVE_HOST_COMPLETE;
} else if (factory_->HasMatchingIpSession(
key_,
HostResolver::GetNonProtocolEndpoints(
*fresh_resolve_host_request_->GetEndpointResults()),
*fresh_resolve_host_request_->GetDnsAliasResults(),
use_dns_aliases_)) {
// TODO(crbug.com/1264933): Consider dealing with the other
// endpoints with protocol metadata.
// Session with resolved IP has already existed, so close racing
// connection, run callback, and return.
LogRacingStatus(ConnectionStateAfterDNS::kIpPooled);
LogConnectionIpPooling(true);
CloseStaleHostConnection();
if (!callback_.is_null())
std::move(callback_).Run(OK);
return;
} else if (io_state_ != STATE_HOST_VALIDATION) {
// Case where host resolution returns successfully, but stale connection
// hasn't finished yet.
if (DoesConnectionMatchFreshHostResolution()) {
LogRacingStatus(ConnectionStateAfterDNS::kWaitingForCryptoDnsMatched);
LogStaleAndFreshHostMatched(true);
fresh_resolve_host_request_ = nullptr;
return;
}
LogRacingStatus(ConnectionStateAfterDNS::kWaitingForCryptoDnsNoMatch);
LogStaleAndFreshHostMatched(false);
CloseStaleHostConnection();
resolve_host_request_ = std::move(fresh_resolve_host_request_);
io_state_ = STATE_RESOLVE_HOST_COMPLETE;
} // Else stale connection has already finished successfully.
} else {
// If not in DNS race, we should have been waiting for this callback in
// STATE_RESOLVE_HOST_COMPLETE.
DCHECK_EQ(STATE_RESOLVE_HOST_COMPLETE, io_state_);
}
rv = DoLoop(rv);
// Expect to be marked by either DoResolveHostComplete() or DoValidateHost().
DCHECK(host_resolution_finished_);
// DNS race should be completed either above or by DoValidateHost().
DCHECK(!fresh_resolve_host_request_);
for (auto* request : stream_requests_) {
request->OnHostResolutionComplete(rv);
}
if (rv != ERR_IO_PENDING && !callback_.is_null())
std::move(callback_).Run(rv);
}
void QuicStreamFactory::Job::OnCryptoConnectComplete(int rv) {
// This early return will be triggered when CloseSessionOnError is called
// before crypto handshake has completed.
if (!session_) {
LogStaleConnectionTime(quic_connection_start_time_);
return;
}
if (rv == ERR_QUIC_PROTOCOL_ERROR) {
HistogramProtocolErrorLocation(
JobProtocolErrorLocation::kCryptoConnectFailedAsync);
}
io_state_ = STATE_CONNECT_COMPLETE;
rv = DoLoop(rv);
if (rv != ERR_IO_PENDING && !callback_.is_null())
std::move(callback_).Run(rv);
}
void QuicStreamFactory::Job::PopulateNetErrorDetails(
NetErrorDetails* details) const {
if (!session_)
return;
details->connection_info = QuicHttpStream::ConnectionInfoFromQuicVersion(
session_->connection()->version());
details->quic_connection_error = session_->error();
}
int QuicStreamFactory::Job::DoResolveHost() {
dns_resolution_start_time_ = base::TimeTicks::Now();
io_state_ = STATE_RESOLVE_HOST_COMPLETE;
HostResolver::ResolveHostParameters parameters;
parameters.initial_priority = priority_;
if (race_stale_dns_on_connection_) {
// Allow host resolver to return stale result immediately.
parameters.cache_usage =
HostResolver::ResolveHostParameters::CacheUsage::STALE_ALLOWED;
}
parameters.secure_dns_policy = key_.session_key().secure_dns_policy();
resolve_host_request_ = host_resolver_->CreateRequest(
key_.destination(), key_.session_key().network_anonymization_key(),
net_log_, parameters);
// Unretained is safe because |this| owns the request, ensuring cancellation
// on destruction.
// When race_stale_dns_on_connection_ is on, this request will query for stale
// cache if no fresh host result is available.
int rv = resolve_host_request_->Start(base::BindOnce(
&QuicStreamFactory::Job::OnResolveHostComplete, base::Unretained(this)));
if (rv == ERR_IO_PENDING || !resolve_host_request_->GetStaleInfo() ||
!resolve_host_request_->GetStaleInfo().value().is_stale()) {
// Returns non-stale result synchronously.
if (rv != ERR_IO_PENDING) {
LogFreshDnsResolveTime(dns_resolution_start_time_);
}
// Not a stale result.
if (race_stale_dns_on_connection_)
LogStaleHostRacing(false);
return rv;
}
// If request resulted in a stale cache entry, start request for fresh results
DCHECK(race_stale_dns_on_connection_);
parameters.cache_usage =
HostResolver::ResolveHostParameters::CacheUsage::DISALLOWED;
fresh_resolve_host_request_ = host_resolver_->CreateRequest(
key_.destination(), key_.session_key().network_anonymization_key(),
net_log_, parameters);
// Unretained is safe because |this| owns the request, ensuring cancellation
// on destruction.
// This request will only query fresh host resolution.
int fresh_rv = fresh_resolve_host_request_->Start(base::BindOnce(
&QuicStreamFactory::Job::OnResolveHostComplete, base::Unretained(this)));
if (fresh_rv != ERR_IO_PENDING) {
// Fresh request returned immediate results.
LogFreshDnsResolveTime(dns_resolution_start_time_);
LogStaleHostRacing(false);
resolve_host_request_ = std::move(fresh_resolve_host_request_);
return fresh_rv;
}
// Check to make sure stale host request does produce valid results.
if (!resolve_host_request_->GetEndpointResults()) {
LogStaleHostRacing(false);
resolve_host_request_ = std::move(fresh_resolve_host_request_);
return fresh_rv;
}
// No fresh host resolution is available at this time, but there is available
// stale result. End time for stale host resolution is recorded and connection
// from stale host will be tried.
dns_resolution_end_time_ = base::TimeTicks().Now();
io_state_ = STATE_CREATE_SESSION;
create_session_on_stale_dns_ = true;
LogStaleHostRacing(true);
return OK;
}
int QuicStreamFactory::Job::DoResolveHostComplete(int rv) {
host_resolution_finished_ = true;
dns_resolution_end_time_ = base::TimeTicks::Now();
if (rv != OK)
return rv;
DCHECK(!fresh_resolve_host_request_);
DCHECK(!factory_->HasActiveSession(key_.session_key()));
// Inform the factory of this resolution, which will set up
// a session alias, if possible.
// TODO(crbug.com/1264933): Consider dealing with the other endpoints
// with protocol metadata.
if (factory_->HasMatchingIpSession(
key_,
HostResolver::GetNonProtocolEndpoints(
*resolve_host_request_->GetEndpointResults()),
*resolve_host_request_->GetDnsAliasResults(), use_dns_aliases_)) {
LogConnectionIpPooling(true);
return OK;
}
io_state_ = STATE_CREATE_SESSION;
return OK;
}
void QuicStreamFactory::Job::OnCreateSessionComplete(int rv) {
DCHECK(!quic_session_created_);
if (!create_session_on_stale_dns_) {
quic_session_created_ = true;
}
if (rv != OK) {
DCHECK(!session_);
if (rv == ERR_QUIC_PROTOCOL_ERROR) {
HistogramProtocolErrorLocation(
JobProtocolErrorLocation::kCreateSessionFailedAsync);
}
if (!create_session_on_stale_dns_) {
MaybeOnQuicSessionCreationComplete(rv);
} else {
create_session_on_stale_dns_ = false;
}
return;
}
DCHECK(session_);
create_session_on_stale_dns_ = false;
DVLOG(1) << "Created session on network: " << network_;
io_state_ = STATE_CREATE_SESSION_COMPLETE;
rv = DoLoop(rv);
if (host_resolution_finished_) {
for (auto* request : stream_requests_) {
request->OnQuicSessionCreationComplete(rv);
}
}
if (rv != ERR_IO_PENDING && !callback_.is_null()) {
std::move(callback_).Run(rv);
}
}
void QuicStreamFactory::Job::MaybeOnQuicSessionCreationComplete(int rv) {
if (!create_session_on_stale_dns_ && host_resolution_finished_) {
for (auto* request : stream_requests_) {
request->OnQuicSessionCreationComplete(rv);
}
if (!callback_.is_null()) {
std::move(callback_).Run(rv);
}
}
}
int QuicStreamFactory::Job::DoCreateSession() {
// TODO(https://crbug.com/1416409): This logic only knows how to try one
// endpoint result.
bool svcb_optional =
IsSvcbOptional(*resolve_host_request_->GetEndpointResults());
bool found = false;
for (const auto& candidate : *resolve_host_request_->GetEndpointResults()) {
quic::ParsedQuicVersion version =
SelectQuicVersion(candidate, svcb_optional);
if (version.IsKnown()) {
found = true;
quic_version_used_ = version;
endpoint_result_ = candidate;
break;
}
}
if (!found) {
return ERR_DNS_NO_MATCHING_SUPPORTED_ALPN;
}
quic_connection_start_time_ = base::TimeTicks::Now();
DCHECK(dns_resolution_end_time_ != base::TimeTicks());
io_state_ = STATE_CREATE_SESSION_COMPLETE;
bool require_confirmation = was_alternative_service_recently_broken_;
net_log_.AddEntryWithBoolParams(
NetLogEventType::QUIC_STREAM_FACTORY_JOB_CONNECT, NetLogEventPhase::BEGIN,
"require_confirmation", require_confirmation);
DCHECK_NE(quic_version_used_, quic::ParsedQuicVersion::Unsupported());
if (base::FeatureList::IsEnabled(net::features::kAsyncQuicSession)) {
return factory_->CreateSessionAsync(
base::BindOnce(&QuicStreamFactory::Job::OnCreateSessionComplete,
GetWeakPtr()),
key_, quic_version_used_, cert_verify_flags_, require_confirmation,
endpoint_result_, dns_resolution_start_time_, dns_resolution_end_time_,
net_log_, &session_, &network_);
}
int rv = factory_->CreateSessionSync(
key_, quic_version_used_, cert_verify_flags_, require_confirmation,
endpoint_result_, dns_resolution_start_time_, dns_resolution_end_time_,
net_log_, &session_, &network_);
DVLOG(1) << "Created session on network: " << network_;
if (rv == ERR_QUIC_PROTOCOL_ERROR) {
DCHECK(!session_);
HistogramProtocolErrorLocation(
JobProtocolErrorLocation::kCreateSessionFailedSync);
}