• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2012 The Chromium Authors
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_server_properties.h"
6 
7 #include "base/check_op.h"
8 #include "base/containers/adapters.h"
9 #include "base/containers/contains.h"
10 #include "base/feature_list.h"
11 #include "base/functional/bind.h"
12 #include "base/location.h"
13 #include "base/metrics/histogram_macros.h"
14 #include "base/strings/string_util.h"
15 #include "base/strings/stringprintf.h"
16 #include "base/task/single_thread_task_runner.h"
17 #include "base/time/default_clock.h"
18 #include "base/time/default_tick_clock.h"
19 #include "base/values.h"
20 #include "net/base/features.h"
21 #include "net/base/url_util.h"
22 #include "net/http/http_network_session.h"
23 #include "net/http/http_server_properties_manager.h"
24 #include "net/socket/ssl_client_socket.h"
25 #include "net/ssl/ssl_config.h"
26 
27 namespace net {
28 
29 namespace {
30 
31 // Time to wait before starting an update the preferences from the
32 // http_server_properties_impl_ cache. Scheduling another update during this
33 // period will be a no-op.
34 constexpr base::TimeDelta kUpdatePrefsDelay = base::Seconds(60);
35 
NormalizeSchemeHostPort(const url::SchemeHostPort & scheme_host_port)36 url::SchemeHostPort NormalizeSchemeHostPort(
37     const url::SchemeHostPort& scheme_host_port) {
38   if (scheme_host_port.scheme() == url::kWssScheme) {
39     return url::SchemeHostPort(url::kHttpsScheme, scheme_host_port.host(),
40                                scheme_host_port.port());
41   }
42   if (scheme_host_port.scheme() == url::kWsScheme) {
43     return url::SchemeHostPort(url::kHttpScheme, scheme_host_port.host(),
44                                scheme_host_port.port());
45   }
46   return scheme_host_port;
47 }
48 
49 }  // namespace
50 
51 HttpServerProperties::PrefDelegate::~PrefDelegate() = default;
52 
53 HttpServerProperties::ServerInfo::ServerInfo() = default;
54 HttpServerProperties::ServerInfo::ServerInfo(const ServerInfo& server_info) =
55     default;
56 HttpServerProperties::ServerInfo::ServerInfo(ServerInfo&& server_info) =
57     default;
58 HttpServerProperties::ServerInfo::~ServerInfo() = default;
59 
empty() const60 bool HttpServerProperties::ServerInfo::empty() const {
61   return !supports_spdy.has_value() && !alternative_services.has_value() &&
62          !server_network_stats.has_value();
63 }
64 
operator ==(const ServerInfo & other) const65 bool HttpServerProperties::ServerInfo::operator==(
66     const ServerInfo& other) const {
67   return supports_spdy == other.supports_spdy &&
68          alternative_services == other.alternative_services &&
69          server_network_stats == other.server_network_stats;
70 }
71 
ServerInfoMapKey(url::SchemeHostPort server,const NetworkAnonymizationKey & network_anonymization_key,bool use_network_anonymization_key)72 HttpServerProperties::ServerInfoMapKey::ServerInfoMapKey(
73     url::SchemeHostPort server,
74     const NetworkAnonymizationKey& network_anonymization_key,
75     bool use_network_anonymization_key)
76     : server(std::move(server)),
77       network_anonymization_key(use_network_anonymization_key
78                                     ? network_anonymization_key
79                                     : NetworkAnonymizationKey()) {
80   // Scheme should have been normalized before this method was called.
81   DCHECK_NE(this->server.scheme(), url::kWsScheme);
82   DCHECK_NE(this->server.scheme(), url::kWssScheme);
83 }
84 
85 HttpServerProperties::ServerInfoMapKey::~ServerInfoMapKey() = default;
86 
operator <(const ServerInfoMapKey & other) const87 bool HttpServerProperties::ServerInfoMapKey::operator<(
88     const ServerInfoMapKey& other) const {
89   return std::tie(server, network_anonymization_key) <
90          std::tie(other.server, other.network_anonymization_key);
91 }
92 
QuicServerInfoMapKey(const quic::QuicServerId & server_id,const NetworkAnonymizationKey & network_anonymization_key,bool use_network_anonymization_key)93 HttpServerProperties::QuicServerInfoMapKey::QuicServerInfoMapKey(
94     const quic::QuicServerId& server_id,
95     const NetworkAnonymizationKey& network_anonymization_key,
96     bool use_network_anonymization_key)
97     : server_id(server_id),
98       network_anonymization_key(use_network_anonymization_key
99                                     ? network_anonymization_key
100                                     : NetworkAnonymizationKey()) {}
101 
102 HttpServerProperties::QuicServerInfoMapKey::~QuicServerInfoMapKey() = default;
103 
operator <(const QuicServerInfoMapKey & other) const104 bool HttpServerProperties::QuicServerInfoMapKey::operator<(
105     const QuicServerInfoMapKey& other) const {
106   return std::tie(server_id, network_anonymization_key) <
107          std::tie(other.server_id, other.network_anonymization_key);
108 }
109 
110 // Used in tests.
operator ==(const QuicServerInfoMapKey & other) const111 bool HttpServerProperties::QuicServerInfoMapKey::operator==(
112     const QuicServerInfoMapKey& other) const {
113   return std::tie(server_id, network_anonymization_key) ==
114          std::tie(other.server_id, other.network_anonymization_key);
115 }
116 
ServerInfoMap()117 HttpServerProperties::ServerInfoMap::ServerInfoMap()
118     : base::LRUCache<ServerInfoMapKey, ServerInfo>(kMaxServerInfoEntries) {}
119 
120 HttpServerProperties::ServerInfoMap::iterator
GetOrPut(const ServerInfoMapKey & key)121 HttpServerProperties::ServerInfoMap::GetOrPut(const ServerInfoMapKey& key) {
122   auto it = Get(key);
123   if (it != end())
124     return it;
125   return Put(key, ServerInfo());
126 }
127 
128 HttpServerProperties::ServerInfoMap::iterator
EraseIfEmpty(iterator server_info_it)129 HttpServerProperties::ServerInfoMap::EraseIfEmpty(iterator server_info_it) {
130   if (server_info_it->second.empty())
131     return Erase(server_info_it);
132   return ++server_info_it;
133 }
134 
HttpServerProperties(std::unique_ptr<PrefDelegate> pref_delegate,NetLog * net_log,const base::TickClock * tick_clock,base::Clock * clock)135 HttpServerProperties::HttpServerProperties(
136     std::unique_ptr<PrefDelegate> pref_delegate,
137     NetLog* net_log,
138     const base::TickClock* tick_clock,
139     base::Clock* clock)
140     : tick_clock_(tick_clock ? tick_clock
141                              : base::DefaultTickClock::GetInstance()),
142       clock_(clock ? clock : base::DefaultClock::GetInstance()),
143       use_network_anonymization_key_(
144           NetworkAnonymizationKey::IsPartitioningEnabled()),
145       is_initialized_(pref_delegate.get() == nullptr),
146       properties_manager_(
147           pref_delegate
148               ? std::make_unique<HttpServerPropertiesManager>(
149                     std::move(pref_delegate),
150                     base::BindOnce(&HttpServerProperties::OnPrefsLoaded,
151                                    base::Unretained(this)),
152                     kDefaultMaxQuicServerEntries,
153                     net_log,
154                     tick_clock_)
155               : nullptr),
156       broken_alternative_services_(kMaxRecentlyBrokenAlternativeServiceEntries,
157                                    this,
158                                    tick_clock_),
159       canonical_suffixes_({".ggpht.com", ".c.youtube.com", ".googlevideo.com",
160                            ".googleusercontent.com", ".gvt1.com"}),
161       quic_server_info_map_(kDefaultMaxQuicServerEntries),
162       max_server_configs_stored_in_properties_(kDefaultMaxQuicServerEntries) {}
163 
~HttpServerProperties()164 HttpServerProperties::~HttpServerProperties() {
165   DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
166 
167   if (properties_manager_) {
168     // Stop waiting for initial settings.
169     is_initialized_ = true;
170 
171     // Stop the timer if it's running, since this will write to the properties
172     // file immediately.
173     prefs_update_timer_.Stop();
174 
175     WriteProperties(base::OnceClosure());
176   }
177 }
178 
Clear(base::OnceClosure callback)179 void HttpServerProperties::Clear(base::OnceClosure callback) {
180   DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
181   server_info_map_.Clear();
182   broken_alternative_services_.Clear();
183   canonical_alt_svc_map_.clear();
184   last_local_address_when_quic_worked_ = IPAddress();
185   quic_server_info_map_.Clear();
186   canonical_server_info_map_.clear();
187 
188   if (properties_manager_) {
189     // Stop waiting for initial settings.
190     is_initialized_ = true;
191     // Leaving this as-is doesn't actually have any effect, if it's true, but
192     // seems best to be safe.
193     queue_write_on_load_ = false;
194 
195     // Stop the timer if it's running, since this will write to the properties
196     // file immediately.
197     prefs_update_timer_.Stop();
198     WriteProperties(std::move(callback));
199   } else if (callback) {
200     base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
201         FROM_HERE, std::move(callback));
202   }
203 }
204 
SupportsRequestPriority(const url::SchemeHostPort & server,const net::NetworkAnonymizationKey & network_anonymization_key)205 bool HttpServerProperties::SupportsRequestPriority(
206     const url::SchemeHostPort& server,
207     const net::NetworkAnonymizationKey& network_anonymization_key) {
208   DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
209   if (server.host().empty())
210     return false;
211 
212   if (GetSupportsSpdy(server, network_anonymization_key))
213     return true;
214   const AlternativeServiceInfoVector alternative_service_info_vector =
215       GetAlternativeServiceInfos(server, network_anonymization_key);
216   for (const AlternativeServiceInfo& alternative_service_info :
217        alternative_service_info_vector) {
218     if (alternative_service_info.alternative_service().protocol == kProtoQUIC) {
219       return true;
220     }
221   }
222   return false;
223 }
224 
GetSupportsSpdy(const url::SchemeHostPort & server,const net::NetworkAnonymizationKey & network_anonymization_key)225 bool HttpServerProperties::GetSupportsSpdy(
226     const url::SchemeHostPort& server,
227     const net::NetworkAnonymizationKey& network_anonymization_key) {
228   DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
229   return GetSupportsSpdyInternal(NormalizeSchemeHostPort(server),
230                                  network_anonymization_key);
231 }
232 
SetSupportsSpdy(const url::SchemeHostPort & server,const net::NetworkAnonymizationKey & network_anonymization_key,bool supports_spdy)233 void HttpServerProperties::SetSupportsSpdy(
234     const url::SchemeHostPort& server,
235     const net::NetworkAnonymizationKey& network_anonymization_key,
236     bool supports_spdy) {
237   DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
238   SetSupportsSpdyInternal(NormalizeSchemeHostPort(server),
239                           network_anonymization_key, supports_spdy);
240 }
241 
RequiresHTTP11(const url::SchemeHostPort & server,const net::NetworkAnonymizationKey & network_anonymization_key)242 bool HttpServerProperties::RequiresHTTP11(
243     const url::SchemeHostPort& server,
244     const net::NetworkAnonymizationKey& network_anonymization_key) {
245   DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
246   return RequiresHTTP11Internal(NormalizeSchemeHostPort(server),
247                                 network_anonymization_key);
248 }
249 
SetHTTP11Required(const url::SchemeHostPort & server,const net::NetworkAnonymizationKey & network_anonymization_key)250 void HttpServerProperties::SetHTTP11Required(
251     const url::SchemeHostPort& server,
252     const net::NetworkAnonymizationKey& network_anonymization_key) {
253   DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
254   SetHTTP11RequiredInternal(NormalizeSchemeHostPort(server),
255                             network_anonymization_key);
256 }
257 
MaybeForceHTTP11(const url::SchemeHostPort & server,const net::NetworkAnonymizationKey & network_anonymization_key,SSLConfig * ssl_config)258 void HttpServerProperties::MaybeForceHTTP11(
259     const url::SchemeHostPort& server,
260     const net::NetworkAnonymizationKey& network_anonymization_key,
261     SSLConfig* ssl_config) {
262   DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
263   MaybeForceHTTP11Internal(NormalizeSchemeHostPort(server),
264                            network_anonymization_key, ssl_config);
265 }
266 
GetAlternativeServiceInfos(const url::SchemeHostPort & origin,const net::NetworkAnonymizationKey & network_anonymization_key)267 AlternativeServiceInfoVector HttpServerProperties::GetAlternativeServiceInfos(
268     const url::SchemeHostPort& origin,
269     const net::NetworkAnonymizationKey& network_anonymization_key) {
270   DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
271   return GetAlternativeServiceInfosInternal(NormalizeSchemeHostPort(origin),
272                                             network_anonymization_key);
273 }
274 
SetHttp2AlternativeService(const url::SchemeHostPort & origin,const NetworkAnonymizationKey & network_anonymization_key,const AlternativeService & alternative_service,base::Time expiration)275 void HttpServerProperties::SetHttp2AlternativeService(
276     const url::SchemeHostPort& origin,
277     const NetworkAnonymizationKey& network_anonymization_key,
278     const AlternativeService& alternative_service,
279     base::Time expiration) {
280   DCHECK_EQ(alternative_service.protocol, kProtoHTTP2);
281 
282   SetAlternativeServices(
283       origin, network_anonymization_key,
284       AlternativeServiceInfoVector(
285           /*size=*/1, AlternativeServiceInfo::CreateHttp2AlternativeServiceInfo(
286                           alternative_service, expiration)));
287 }
288 
SetQuicAlternativeService(const url::SchemeHostPort & origin,const NetworkAnonymizationKey & network_anonymization_key,const AlternativeService & alternative_service,base::Time expiration,const quic::ParsedQuicVersionVector & advertised_versions)289 void HttpServerProperties::SetQuicAlternativeService(
290     const url::SchemeHostPort& origin,
291     const NetworkAnonymizationKey& network_anonymization_key,
292     const AlternativeService& alternative_service,
293     base::Time expiration,
294     const quic::ParsedQuicVersionVector& advertised_versions) {
295   DCHECK(alternative_service.protocol == kProtoQUIC);
296 
297   SetAlternativeServices(
298       origin, network_anonymization_key,
299       AlternativeServiceInfoVector(
300           /*size=*/1,
301           AlternativeServiceInfo::CreateQuicAlternativeServiceInfo(
302               alternative_service, expiration, advertised_versions)));
303 }
304 
SetAlternativeServices(const url::SchemeHostPort & origin,const net::NetworkAnonymizationKey & network_anonymization_key,const AlternativeServiceInfoVector & alternative_service_info_vector)305 void HttpServerProperties::SetAlternativeServices(
306     const url::SchemeHostPort& origin,
307     const net::NetworkAnonymizationKey& network_anonymization_key,
308     const AlternativeServiceInfoVector& alternative_service_info_vector) {
309   DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
310   SetAlternativeServicesInternal(NormalizeSchemeHostPort(origin),
311                                  network_anonymization_key,
312                                  alternative_service_info_vector);
313 }
314 
MarkAlternativeServiceBroken(const AlternativeService & alternative_service,const net::NetworkAnonymizationKey & network_anonymization_key)315 void HttpServerProperties::MarkAlternativeServiceBroken(
316     const AlternativeService& alternative_service,
317     const net::NetworkAnonymizationKey& network_anonymization_key) {
318   broken_alternative_services_.MarkBroken(
319       BrokenAlternativeService(alternative_service, network_anonymization_key,
320                                use_network_anonymization_key_));
321   MaybeQueueWriteProperties();
322 }
323 
324 void HttpServerProperties::
MarkAlternativeServiceBrokenUntilDefaultNetworkChanges(const AlternativeService & alternative_service,const net::NetworkAnonymizationKey & network_anonymization_key)325     MarkAlternativeServiceBrokenUntilDefaultNetworkChanges(
326         const AlternativeService& alternative_service,
327         const net::NetworkAnonymizationKey& network_anonymization_key) {
328   broken_alternative_services_.MarkBrokenUntilDefaultNetworkChanges(
329       BrokenAlternativeService(alternative_service, network_anonymization_key,
330                                use_network_anonymization_key_));
331   MaybeQueueWriteProperties();
332 }
333 
MarkAlternativeServiceRecentlyBroken(const AlternativeService & alternative_service,const net::NetworkAnonymizationKey & network_anonymization_key)334 void HttpServerProperties::MarkAlternativeServiceRecentlyBroken(
335     const AlternativeService& alternative_service,
336     const net::NetworkAnonymizationKey& network_anonymization_key) {
337   broken_alternative_services_.MarkRecentlyBroken(
338       BrokenAlternativeService(alternative_service, network_anonymization_key,
339                                use_network_anonymization_key_));
340   MaybeQueueWriteProperties();
341 }
342 
IsAlternativeServiceBroken(const AlternativeService & alternative_service,const net::NetworkAnonymizationKey & network_anonymization_key) const343 bool HttpServerProperties::IsAlternativeServiceBroken(
344     const AlternativeService& alternative_service,
345     const net::NetworkAnonymizationKey& network_anonymization_key) const {
346   return broken_alternative_services_.IsBroken(
347       BrokenAlternativeService(alternative_service, network_anonymization_key,
348                                use_network_anonymization_key_));
349 }
350 
WasAlternativeServiceRecentlyBroken(const AlternativeService & alternative_service,const net::NetworkAnonymizationKey & network_anonymization_key)351 bool HttpServerProperties::WasAlternativeServiceRecentlyBroken(
352     const AlternativeService& alternative_service,
353     const net::NetworkAnonymizationKey& network_anonymization_key) {
354   return broken_alternative_services_.WasRecentlyBroken(
355       BrokenAlternativeService(alternative_service, network_anonymization_key,
356                                use_network_anonymization_key_));
357 }
358 
ConfirmAlternativeService(const AlternativeService & alternative_service,const net::NetworkAnonymizationKey & network_anonymization_key)359 void HttpServerProperties::ConfirmAlternativeService(
360     const AlternativeService& alternative_service,
361     const net::NetworkAnonymizationKey& network_anonymization_key) {
362   bool old_value = IsAlternativeServiceBroken(alternative_service,
363                                               network_anonymization_key);
364   broken_alternative_services_.Confirm(
365       BrokenAlternativeService(alternative_service, network_anonymization_key,
366                                use_network_anonymization_key_));
367   bool new_value = IsAlternativeServiceBroken(alternative_service,
368                                               network_anonymization_key);
369 
370   // For persisting, we only care about the value returned by
371   // IsAlternativeServiceBroken. If that value changes, then call persist.
372   if (old_value != new_value)
373     MaybeQueueWriteProperties();
374 }
375 
OnDefaultNetworkChanged()376 void HttpServerProperties::OnDefaultNetworkChanged() {
377   bool changed = broken_alternative_services_.OnDefaultNetworkChanged();
378   if (changed)
379     MaybeQueueWriteProperties();
380 }
381 
GetAlternativeServiceInfoAsValue() const382 base::Value HttpServerProperties::GetAlternativeServiceInfoAsValue() const {
383   const base::Time now = clock_->Now();
384   const base::TimeTicks now_ticks = tick_clock_->NowTicks();
385   base::Value::List dict_list;
386   for (const auto& server_info : server_info_map_) {
387     if (!server_info.second.alternative_services.has_value())
388       continue;
389     base::Value::List alternative_service_list;
390     const ServerInfoMapKey& key = server_info.first;
391     for (const AlternativeServiceInfo& alternative_service_info :
392          server_info.second.alternative_services.value()) {
393       std::string alternative_service_string(
394           alternative_service_info.ToString());
395       AlternativeService alternative_service(
396           alternative_service_info.alternative_service());
397       if (alternative_service.host.empty()) {
398         alternative_service.host = key.server.host();
399       }
400       base::TimeTicks brokenness_expiration_ticks;
401       if (broken_alternative_services_.IsBroken(
402               BrokenAlternativeService(
403                   alternative_service,
404                   server_info.first.network_anonymization_key,
405                   use_network_anonymization_key_),
406               &brokenness_expiration_ticks)) {
407         // Convert |brokenness_expiration| from TimeTicks to Time
408         base::Time brokenness_expiration =
409             now + (brokenness_expiration_ticks - now_ticks);
410         base::Time::Exploded exploded;
411         brokenness_expiration.LocalExplode(&exploded);
412         std::string broken_info_string =
413             " (broken until " +
414             base::StringPrintf("%04d-%02d-%02d %0d:%0d:%0d", exploded.year,
415                                exploded.month, exploded.day_of_month,
416                                exploded.hour, exploded.minute,
417                                exploded.second) +
418             ")";
419         alternative_service_string.append(broken_info_string);
420       }
421       alternative_service_list.Append(std::move(alternative_service_string));
422     }
423     if (alternative_service_list.empty())
424       continue;
425     base::Value::Dict dict;
426     dict.Set("server", key.server.Serialize());
427     dict.Set("network_anonymization_key",
428              key.network_anonymization_key.ToDebugString());
429     dict.Set("alternative_service", std::move(alternative_service_list));
430     dict_list.Append(std::move(dict));
431   }
432   return base::Value(std::move(dict_list));
433 }
434 
WasLastLocalAddressWhenQuicWorked(const IPAddress & local_address) const435 bool HttpServerProperties::WasLastLocalAddressWhenQuicWorked(
436     const IPAddress& local_address) const {
437   return !last_local_address_when_quic_worked_.empty() &&
438          last_local_address_when_quic_worked_ == local_address;
439 }
440 
HasLastLocalAddressWhenQuicWorked() const441 bool HttpServerProperties::HasLastLocalAddressWhenQuicWorked() const {
442   return !last_local_address_when_quic_worked_.empty();
443 }
444 
SetLastLocalAddressWhenQuicWorked(IPAddress last_local_address_when_quic_worked)445 void HttpServerProperties::SetLastLocalAddressWhenQuicWorked(
446     IPAddress last_local_address_when_quic_worked) {
447   DCHECK(!last_local_address_when_quic_worked.empty());
448   if (last_local_address_when_quic_worked_ ==
449       last_local_address_when_quic_worked) {
450     return;
451   }
452 
453   last_local_address_when_quic_worked_ = last_local_address_when_quic_worked;
454   MaybeQueueWriteProperties();
455 }
456 
ClearLastLocalAddressWhenQuicWorked()457 void HttpServerProperties::ClearLastLocalAddressWhenQuicWorked() {
458   if (last_local_address_when_quic_worked_.empty())
459     return;
460 
461   last_local_address_when_quic_worked_ = IPAddress();
462   MaybeQueueWriteProperties();
463 }
464 
SetServerNetworkStats(const url::SchemeHostPort & server,const NetworkAnonymizationKey & network_anonymization_key,ServerNetworkStats stats)465 void HttpServerProperties::SetServerNetworkStats(
466     const url::SchemeHostPort& server,
467     const NetworkAnonymizationKey& network_anonymization_key,
468     ServerNetworkStats stats) {
469   SetServerNetworkStatsInternal(NormalizeSchemeHostPort(server),
470                                 network_anonymization_key, std::move(stats));
471 }
472 
ClearServerNetworkStats(const url::SchemeHostPort & server,const NetworkAnonymizationKey & network_anonymization_key)473 void HttpServerProperties::ClearServerNetworkStats(
474     const url::SchemeHostPort& server,
475     const NetworkAnonymizationKey& network_anonymization_key) {
476   ClearServerNetworkStatsInternal(NormalizeSchemeHostPort(server),
477                                   network_anonymization_key);
478 }
479 
GetServerNetworkStats(const url::SchemeHostPort & server,const NetworkAnonymizationKey & network_anonymization_key)480 const ServerNetworkStats* HttpServerProperties::GetServerNetworkStats(
481     const url::SchemeHostPort& server,
482     const NetworkAnonymizationKey& network_anonymization_key) {
483   return GetServerNetworkStatsInternal(NormalizeSchemeHostPort(server),
484                                        network_anonymization_key);
485 }
486 
SetQuicServerInfo(const quic::QuicServerId & server_id,const NetworkAnonymizationKey & network_anonymization_key,const std::string & server_info)487 void HttpServerProperties::SetQuicServerInfo(
488     const quic::QuicServerId& server_id,
489     const NetworkAnonymizationKey& network_anonymization_key,
490     const std::string& server_info) {
491   QuicServerInfoMapKey key =
492       CreateQuicServerInfoKey(server_id, network_anonymization_key);
493   auto it = quic_server_info_map_.Peek(key);
494   bool changed =
495       (it == quic_server_info_map_.end() || it->second != server_info);
496   quic_server_info_map_.Put(key, server_info);
497   UpdateCanonicalServerInfoMap(key);
498   if (changed)
499     MaybeQueueWriteProperties();
500 }
501 
GetQuicServerInfo(const quic::QuicServerId & server_id,const NetworkAnonymizationKey & network_anonymization_key)502 const std::string* HttpServerProperties::GetQuicServerInfo(
503     const quic::QuicServerId& server_id,
504     const NetworkAnonymizationKey& network_anonymization_key) {
505   QuicServerInfoMapKey key =
506       CreateQuicServerInfoKey(server_id, network_anonymization_key);
507   auto it = quic_server_info_map_.Get(key);
508   if (it != quic_server_info_map_.end()) {
509     // Since |canonical_server_info_map_| should always map to the most
510     // recent host, update it with the one that became MRU in
511     // |quic_server_info_map_|.
512     UpdateCanonicalServerInfoMap(key);
513     return &it->second;
514   }
515 
516   // If the exact match for |server_id| wasn't found, check
517   // |canonical_server_info_map_| whether there is server info for a host with
518   // the same canonical host suffix.
519   auto canonical_itr = GetCanonicalServerInfoHost(key);
520   if (canonical_itr == canonical_server_info_map_.end())
521     return nullptr;
522 
523   // When search in |quic_server_info_map_|, do not change the MRU order.
524   it = quic_server_info_map_.Peek(CreateQuicServerInfoKey(
525       canonical_itr->second, network_anonymization_key));
526   if (it != quic_server_info_map_.end())
527     return &it->second;
528 
529   return nullptr;
530 }
531 
532 const HttpServerProperties::QuicServerInfoMap&
quic_server_info_map() const533 HttpServerProperties::quic_server_info_map() const {
534   return quic_server_info_map_;
535 }
536 
max_server_configs_stored_in_properties() const537 size_t HttpServerProperties::max_server_configs_stored_in_properties() const {
538   return max_server_configs_stored_in_properties_;
539 }
540 
SetMaxServerConfigsStoredInProperties(size_t max_server_configs_stored_in_properties)541 void HttpServerProperties::SetMaxServerConfigsStoredInProperties(
542     size_t max_server_configs_stored_in_properties) {
543   // Do nothing if the new size is the same as the old one.
544   if (max_server_configs_stored_in_properties_ ==
545       max_server_configs_stored_in_properties) {
546     return;
547   }
548 
549   max_server_configs_stored_in_properties_ =
550       max_server_configs_stored_in_properties;
551 
552   // LRUCache doesn't allow the capacity of the cache to be changed. Thus create
553   // a new map with the new size and add current elements and swap the new map.
554   quic_server_info_map_.ShrinkToSize(max_server_configs_stored_in_properties_);
555   QuicServerInfoMap temp_map(max_server_configs_stored_in_properties_);
556   // Update the |canonical_server_info_map_| as well, so it stays in sync with
557   // |quic_server_info_map_|.
558   canonical_server_info_map_ = QuicCanonicalMap();
559   for (const auto& [key, server_info] : base::Reversed(quic_server_info_map_)) {
560     temp_map.Put(key, server_info);
561     UpdateCanonicalServerInfoMap(key);
562   }
563 
564   quic_server_info_map_.Swap(temp_map);
565   if (properties_manager_) {
566     properties_manager_->set_max_server_configs_stored_in_properties(
567         max_server_configs_stored_in_properties);
568   }
569 }
570 
SetBrokenAlternativeServicesDelayParams(absl::optional<base::TimeDelta> initial_delay,absl::optional<bool> exponential_backoff_on_initial_delay)571 void HttpServerProperties::SetBrokenAlternativeServicesDelayParams(
572     absl::optional<base::TimeDelta> initial_delay,
573     absl::optional<bool> exponential_backoff_on_initial_delay) {
574   broken_alternative_services_.SetDelayParams(
575       initial_delay, exponential_backoff_on_initial_delay);
576 }
577 
IsInitialized() const578 bool HttpServerProperties::IsInitialized() const {
579   return is_initialized_;
580 }
581 
OnExpireBrokenAlternativeService(const AlternativeService & expired_alternative_service,const NetworkAnonymizationKey & network_anonymization_key)582 void HttpServerProperties::OnExpireBrokenAlternativeService(
583     const AlternativeService& expired_alternative_service,
584     const NetworkAnonymizationKey& network_anonymization_key) {
585   // Remove every occurrence of |expired_alternative_service| from
586   // |alternative_service_map_|.
587   for (auto map_it = server_info_map_.begin();
588        map_it != server_info_map_.end();) {
589     if (!map_it->second.alternative_services.has_value() ||
590         map_it->first.network_anonymization_key != network_anonymization_key) {
591       ++map_it;
592       continue;
593     }
594     AlternativeServiceInfoVector* service_info =
595         &map_it->second.alternative_services.value();
596     for (auto it = service_info->begin(); it != service_info->end();) {
597       AlternativeService alternative_service(it->alternative_service());
598       // Empty hostname in map means hostname of key: substitute before
599       // comparing to |expired_alternative_service|.
600       if (alternative_service.host.empty()) {
601         alternative_service.host = map_it->first.server.host();
602       }
603       if (alternative_service == expired_alternative_service) {
604         it = service_info->erase(it);
605         continue;
606       }
607       ++it;
608     }
609     // If an origin has an empty list of alternative services, then remove it
610     // from both |canonical_alt_svc_map_| and
611     // |alternative_service_map_|.
612     if (service_info->empty()) {
613       RemoveAltSvcCanonicalHost(map_it->first.server,
614                                 network_anonymization_key);
615       map_it->second.alternative_services.reset();
616       map_it = server_info_map_.EraseIfEmpty(map_it);
617       continue;
618     }
619     ++map_it;
620   }
621 }
622 
GetUpdatePrefsDelayForTesting()623 base::TimeDelta HttpServerProperties::GetUpdatePrefsDelayForTesting() {
624   return kUpdatePrefsDelay;
625 }
626 
GetSupportsSpdyInternal(url::SchemeHostPort server,const net::NetworkAnonymizationKey & network_anonymization_key)627 bool HttpServerProperties::GetSupportsSpdyInternal(
628     url::SchemeHostPort server,
629     const net::NetworkAnonymizationKey& network_anonymization_key) {
630   DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
631   DCHECK_NE(server.scheme(), url::kWsScheme);
632   DCHECK_NE(server.scheme(), url::kWssScheme);
633   if (server.host().empty())
634     return false;
635 
636   auto server_info = server_info_map_.Get(
637       CreateServerInfoKey(std::move(server), network_anonymization_key));
638   return server_info != server_info_map_.end() &&
639          server_info->second.supports_spdy.value_or(false);
640 }
641 
SetSupportsSpdyInternal(url::SchemeHostPort server,const net::NetworkAnonymizationKey & network_anonymization_key,bool supports_spdy)642 void HttpServerProperties::SetSupportsSpdyInternal(
643     url::SchemeHostPort server,
644     const net::NetworkAnonymizationKey& network_anonymization_key,
645     bool supports_spdy) {
646   DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
647   DCHECK_NE(server.scheme(), url::kWsScheme);
648   DCHECK_NE(server.scheme(), url::kWssScheme);
649   if (server.host().empty())
650     return;
651 
652   auto server_info = server_info_map_.GetOrPut(
653       CreateServerInfoKey(std::move(server), network_anonymization_key));
654   // If value is already the same as |supports_spdy|, or value is unset and
655   // |supports_spdy| is false, don't queue a write.
656   bool queue_write =
657       server_info->second.supports_spdy.value_or(false) != supports_spdy;
658   server_info->second.supports_spdy = supports_spdy;
659 
660   if (queue_write)
661     MaybeQueueWriteProperties();
662 }
663 
RequiresHTTP11Internal(url::SchemeHostPort server,const net::NetworkAnonymizationKey & network_anonymization_key)664 bool HttpServerProperties::RequiresHTTP11Internal(
665     url::SchemeHostPort server,
666     const net::NetworkAnonymizationKey& network_anonymization_key) {
667   DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
668   DCHECK_NE(server.scheme(), url::kWsScheme);
669   DCHECK_NE(server.scheme(), url::kWssScheme);
670   if (server.host().empty())
671     return false;
672 
673   auto spdy_info = server_info_map_.Get(
674       CreateServerInfoKey(std::move(server), network_anonymization_key));
675   return spdy_info != server_info_map_.end() &&
676          spdy_info->second.requires_http11.value_or(false);
677 }
678 
SetHTTP11RequiredInternal(url::SchemeHostPort server,const net::NetworkAnonymizationKey & network_anonymization_key)679 void HttpServerProperties::SetHTTP11RequiredInternal(
680     url::SchemeHostPort server,
681     const net::NetworkAnonymizationKey& network_anonymization_key) {
682   DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
683   DCHECK_NE(server.scheme(), url::kWsScheme);
684   DCHECK_NE(server.scheme(), url::kWssScheme);
685   if (server.host().empty())
686     return;
687 
688   server_info_map_
689       .GetOrPut(
690           CreateServerInfoKey(std::move(server), network_anonymization_key))
691       ->second.requires_http11 = true;
692   // No need to call MaybeQueueWriteProperties(), as this information is not
693   // persisted to preferences.
694 }
695 
MaybeForceHTTP11Internal(url::SchemeHostPort server,const net::NetworkAnonymizationKey & network_anonymization_key,SSLConfig * ssl_config)696 void HttpServerProperties::MaybeForceHTTP11Internal(
697     url::SchemeHostPort server,
698     const net::NetworkAnonymizationKey& network_anonymization_key,
699     SSLConfig* ssl_config) {
700   DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
701   DCHECK_NE(server.scheme(), url::kWsScheme);
702   DCHECK_NE(server.scheme(), url::kWssScheme);
703   if (RequiresHTTP11(std::move(server), network_anonymization_key)) {
704     ssl_config->alpn_protos.clear();
705     ssl_config->alpn_protos.push_back(kProtoHTTP11);
706   }
707 }
708 
709 AlternativeServiceInfoVector
GetAlternativeServiceInfosInternal(const url::SchemeHostPort & origin,const net::NetworkAnonymizationKey & network_anonymization_key)710 HttpServerProperties::GetAlternativeServiceInfosInternal(
711     const url::SchemeHostPort& origin,
712     const net::NetworkAnonymizationKey& network_anonymization_key) {
713   DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
714   DCHECK_NE(origin.scheme(), url::kWsScheme);
715   DCHECK_NE(origin.scheme(), url::kWssScheme);
716 
717   // Copy valid alternative service infos into
718   // |valid_alternative_service_infos|.
719   AlternativeServiceInfoVector valid_alternative_service_infos;
720   const base::Time now = clock_->Now();
721   auto map_it = server_info_map_.Get(
722       CreateServerInfoKey(origin, network_anonymization_key));
723   if (map_it != server_info_map_.end() &&
724       map_it->second.alternative_services.has_value()) {
725     AlternativeServiceInfoVector* service_info =
726         &map_it->second.alternative_services.value();
727     HostPortPair host_port_pair(origin.host(), origin.port());
728     for (auto it = service_info->begin(); it != service_info->end();) {
729       if (it->expiration() < now) {
730         it = service_info->erase(it);
731         continue;
732       }
733       AlternativeService alternative_service(it->alternative_service());
734       if (alternative_service.host.empty()) {
735         alternative_service.host = origin.host();
736       }
737       // If the alternative service is equivalent to the origin (same host, same
738       // port, and both TCP), skip it.
739       if (host_port_pair.Equals(alternative_service.host_port_pair()) &&
740           alternative_service.protocol == kProtoHTTP2) {
741         ++it;
742         continue;
743       }
744       if (alternative_service.protocol == kProtoQUIC) {
745         valid_alternative_service_infos.push_back(
746             AlternativeServiceInfo::CreateQuicAlternativeServiceInfo(
747                 alternative_service, it->expiration(),
748                 it->advertised_versions()));
749       } else {
750         valid_alternative_service_infos.push_back(
751             AlternativeServiceInfo::CreateHttp2AlternativeServiceInfo(
752                 alternative_service, it->expiration()));
753       }
754       ++it;
755     }
756     if (service_info->empty()) {
757       map_it->second.alternative_services.reset();
758       server_info_map_.EraseIfEmpty(map_it);
759     }
760     return valid_alternative_service_infos;
761   }
762 
763   auto canonical = GetCanonicalAltSvcHost(origin, network_anonymization_key);
764   if (canonical == canonical_alt_svc_map_.end()) {
765     return AlternativeServiceInfoVector();
766   }
767   map_it = server_info_map_.Get(
768       CreateServerInfoKey(canonical->second, network_anonymization_key));
769   if (map_it == server_info_map_.end() ||
770       !map_it->second.alternative_services.has_value()) {
771     return AlternativeServiceInfoVector();
772   }
773   AlternativeServiceInfoVector* service_info =
774       &map_it->second.alternative_services.value();
775   for (auto it = service_info->begin(); it != service_info->end();) {
776     if (it->expiration() < now) {
777       it = service_info->erase(it);
778       continue;
779     }
780     AlternativeService alternative_service(it->alternative_service());
781     if (alternative_service.host.empty()) {
782       alternative_service.host = canonical->second.host();
783       if (IsAlternativeServiceBroken(alternative_service,
784                                      network_anonymization_key)) {
785         ++it;
786         continue;
787       }
788       alternative_service.host = origin.host();
789     } else if (IsAlternativeServiceBroken(alternative_service,
790                                           network_anonymization_key)) {
791       ++it;
792       continue;
793     }
794     if (alternative_service.protocol == kProtoQUIC) {
795       valid_alternative_service_infos.push_back(
796           AlternativeServiceInfo::CreateQuicAlternativeServiceInfo(
797               alternative_service, it->expiration(),
798               it->advertised_versions()));
799     } else {
800       valid_alternative_service_infos.push_back(
801           AlternativeServiceInfo::CreateHttp2AlternativeServiceInfo(
802               alternative_service, it->expiration()));
803     }
804     ++it;
805   }
806   if (service_info->empty())
807     server_info_map_.EraseIfEmpty(map_it);
808   return valid_alternative_service_infos;
809 }
810 
SetAlternativeServicesInternal(const url::SchemeHostPort & origin,const net::NetworkAnonymizationKey & network_anonymization_key,const AlternativeServiceInfoVector & alternative_service_info_vector)811 void HttpServerProperties::SetAlternativeServicesInternal(
812     const url::SchemeHostPort& origin,
813     const net::NetworkAnonymizationKey& network_anonymization_key,
814     const AlternativeServiceInfoVector& alternative_service_info_vector) {
815   DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
816   DCHECK_NE(origin.scheme(), url::kWsScheme);
817   DCHECK_NE(origin.scheme(), url::kWssScheme);
818 
819   if (alternative_service_info_vector.empty()) {
820     RemoveAltSvcCanonicalHost(origin, network_anonymization_key);
821     // Don't bother moving to front when erasing information.
822     auto it = server_info_map_.Peek(
823         CreateServerInfoKey(origin, network_anonymization_key));
824 
825     if (it == server_info_map_.end() ||
826         !it->second.alternative_services.has_value()) {
827       return;
828     }
829 
830     it->second.alternative_services.reset();
831     server_info_map_.EraseIfEmpty(it);
832     MaybeQueueWriteProperties();
833     return;
834   }
835 
836   auto it = server_info_map_.GetOrPut(
837       CreateServerInfoKey(origin, network_anonymization_key));
838   bool need_update_pref = true;
839   if (it->second.alternative_services.has_value()) {
840     DCHECK(!it->second.empty());
841     if (it->second.alternative_services->size() ==
842         alternative_service_info_vector.size()) {
843       const base::Time now = clock_->Now();
844       need_update_pref = false;
845       auto new_it = alternative_service_info_vector.begin();
846       for (const auto& old : *it->second.alternative_services) {
847         // Persist to disk immediately if new entry has different scheme, host,
848         // or port.
849         if (old.alternative_service() != new_it->alternative_service()) {
850           need_update_pref = true;
851           break;
852         }
853         // Also persist to disk if new expiration it more that twice as far or
854         // less than half as far in the future.
855         base::Time old_time = old.expiration();
856         base::Time new_time = new_it->expiration();
857         if (new_time - now > 2 * (old_time - now) ||
858             2 * (new_time - now) < (old_time - now)) {
859           need_update_pref = true;
860           break;
861         }
862         // Also persist to disk if new entry has a different list of advertised
863         // versions.
864         if (old.advertised_versions() != new_it->advertised_versions()) {
865           need_update_pref = true;
866           break;
867         }
868         ++new_it;
869       }
870     }
871   }
872 
873   const bool previously_no_alternative_services =
874       (GetIteratorWithAlternativeServiceInfo(
875            origin, network_anonymization_key) == server_info_map_.end());
876 
877   it->second.alternative_services = alternative_service_info_vector;
878 
879   if (previously_no_alternative_services &&
880       !GetAlternativeServiceInfos(origin, network_anonymization_key).empty()) {
881     // TODO(rch): Consider the case where multiple requests are started
882     // before the first completes. In this case, only one of the jobs
883     // would reach this code, whereas all of them should should have.
884     HistogramAlternateProtocolUsage(ALTERNATE_PROTOCOL_USAGE_MAPPING_MISSING,
885                                     IsGoogleHost(origin.host()));
886   }
887 
888   // If this host ends with a canonical suffix, then set it as the
889   // canonical host.
890   const char* kCanonicalScheme = "https";
891   if (origin.scheme() == kCanonicalScheme) {
892     const std::string* canonical_suffix = GetCanonicalSuffix(origin.host());
893     if (canonical_suffix != nullptr) {
894       url::SchemeHostPort canonical_server(kCanonicalScheme, *canonical_suffix,
895                                            origin.port());
896       canonical_alt_svc_map_[CreateServerInfoKey(
897           canonical_server, network_anonymization_key)] = origin;
898     }
899   }
900 
901   if (need_update_pref)
902     MaybeQueueWriteProperties();
903 }
904 
SetServerNetworkStatsInternal(url::SchemeHostPort server,const NetworkAnonymizationKey & network_anonymization_key,ServerNetworkStats stats)905 void HttpServerProperties::SetServerNetworkStatsInternal(
906     url::SchemeHostPort server,
907     const NetworkAnonymizationKey& network_anonymization_key,
908     ServerNetworkStats stats) {
909   DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
910   DCHECK_NE(server.scheme(), url::kWsScheme);
911   DCHECK_NE(server.scheme(), url::kWssScheme);
912 
913   auto server_info = server_info_map_.GetOrPut(
914       CreateServerInfoKey(std::move(server), network_anonymization_key));
915   bool changed = !server_info->second.server_network_stats.has_value() ||
916                  server_info->second.server_network_stats.value() != stats;
917 
918   if (changed) {
919     server_info->second.server_network_stats = stats;
920     MaybeQueueWriteProperties();
921   }
922 }
923 
ClearServerNetworkStatsInternal(url::SchemeHostPort server,const NetworkAnonymizationKey & network_anonymization_key)924 void HttpServerProperties::ClearServerNetworkStatsInternal(
925     url::SchemeHostPort server,
926     const NetworkAnonymizationKey& network_anonymization_key) {
927   auto server_info = server_info_map_.Peek(
928       CreateServerInfoKey(std::move(server), network_anonymization_key));
929   // If stats are empty, nothing to do.
930   if (server_info == server_info_map_.end() ||
931       !server_info->second.server_network_stats.has_value()) {
932     return;
933   }
934 
935   // Otherwise, clear and delete if needed. No need to bring to front of MRU
936   // cache when clearing data.
937   server_info->second.server_network_stats.reset();
938   if (server_info->second.empty())
939     server_info_map_.EraseIfEmpty(server_info);
940   MaybeQueueWriteProperties();
941 }
942 
GetServerNetworkStatsInternal(url::SchemeHostPort server,const NetworkAnonymizationKey & network_anonymization_key)943 const ServerNetworkStats* HttpServerProperties::GetServerNetworkStatsInternal(
944     url::SchemeHostPort server,
945     const NetworkAnonymizationKey& network_anonymization_key) {
946   DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
947   DCHECK_NE(server.scheme(), url::kWsScheme);
948   DCHECK_NE(server.scheme(), url::kWssScheme);
949 
950   auto server_info = server_info_map_.Get(
951       CreateServerInfoKey(std::move(server), network_anonymization_key));
952   if (server_info == server_info_map_.end() ||
953       !server_info->second.server_network_stats.has_value()) {
954     return nullptr;
955   }
956   return &server_info->second.server_network_stats.value();
957 }
958 
959 HttpServerProperties::QuicServerInfoMapKey
CreateQuicServerInfoKey(const quic::QuicServerId & server_id,const NetworkAnonymizationKey & network_anonymization_key) const960 HttpServerProperties::CreateQuicServerInfoKey(
961     const quic::QuicServerId& server_id,
962     const NetworkAnonymizationKey& network_anonymization_key) const {
963   return QuicServerInfoMapKey(server_id, network_anonymization_key,
964                               use_network_anonymization_key_);
965 }
966 
967 HttpServerProperties::ServerInfoMapKey
CreateServerInfoKey(const url::SchemeHostPort & server,const NetworkAnonymizationKey & network_anonymization_key) const968 HttpServerProperties::CreateServerInfoKey(
969     const url::SchemeHostPort& server,
970     const NetworkAnonymizationKey& network_anonymization_key) const {
971   return ServerInfoMapKey(server, network_anonymization_key,
972                           use_network_anonymization_key_);
973 }
974 
975 HttpServerProperties::ServerInfoMap::const_iterator
GetIteratorWithAlternativeServiceInfo(const url::SchemeHostPort & server,const net::NetworkAnonymizationKey & network_anonymization_key)976 HttpServerProperties::GetIteratorWithAlternativeServiceInfo(
977     const url::SchemeHostPort& server,
978     const net::NetworkAnonymizationKey& network_anonymization_key) {
979   ServerInfoMap::const_iterator it = server_info_map_.Get(
980       CreateServerInfoKey(server, network_anonymization_key));
981   if (it != server_info_map_.end() && it->second.alternative_services)
982     return it;
983 
984   auto canonical = GetCanonicalAltSvcHost(server, network_anonymization_key);
985   if (canonical == canonical_alt_svc_map_.end()) {
986     return server_info_map_.end();
987   }
988 
989   const url::SchemeHostPort canonical_server = canonical->second;
990   it = server_info_map_.Get(
991       CreateServerInfoKey(canonical_server, network_anonymization_key));
992   if (it == server_info_map_.end() || !it->second.alternative_services)
993     return server_info_map_.end();
994 
995   for (const AlternativeServiceInfo& alternative_service_info :
996        it->second.alternative_services.value()) {
997     AlternativeService alternative_service(
998         alternative_service_info.alternative_service());
999     if (alternative_service.host.empty()) {
1000       alternative_service.host = canonical_server.host();
1001     }
1002     if (!IsAlternativeServiceBroken(alternative_service,
1003                                     network_anonymization_key)) {
1004       return it;
1005     }
1006   }
1007 
1008   RemoveAltSvcCanonicalHost(canonical_server, network_anonymization_key);
1009   return server_info_map_.end();
1010 }
1011 
1012 HttpServerProperties::CanonicalMap::const_iterator
GetCanonicalAltSvcHost(const url::SchemeHostPort & server,const net::NetworkAnonymizationKey & network_anonymization_key) const1013 HttpServerProperties::GetCanonicalAltSvcHost(
1014     const url::SchemeHostPort& server,
1015     const net::NetworkAnonymizationKey& network_anonymization_key) const {
1016   const char* kCanonicalScheme = "https";
1017   if (server.scheme() != kCanonicalScheme)
1018     return canonical_alt_svc_map_.end();
1019 
1020   const std::string* canonical_suffix = GetCanonicalSuffix(server.host());
1021   if (canonical_suffix == nullptr)
1022     return canonical_alt_svc_map_.end();
1023 
1024   url::SchemeHostPort canonical_server(kCanonicalScheme, *canonical_suffix,
1025                                        server.port());
1026   return canonical_alt_svc_map_.find(
1027       CreateServerInfoKey(canonical_server, network_anonymization_key));
1028 }
1029 
1030 HttpServerProperties::QuicCanonicalMap::const_iterator
GetCanonicalServerInfoHost(const QuicServerInfoMapKey & key) const1031 HttpServerProperties::GetCanonicalServerInfoHost(
1032     const QuicServerInfoMapKey& key) const {
1033   const std::string* canonical_suffix =
1034       GetCanonicalSuffix(key.server_id.host());
1035   if (canonical_suffix == nullptr)
1036     return canonical_server_info_map_.end();
1037 
1038   quic::QuicServerId canonical_server_id(*canonical_suffix,
1039                                          key.server_id.privacy_mode_enabled(),
1040                                          key.server_id.port());
1041   return canonical_server_info_map_.find(CreateQuicServerInfoKey(
1042       canonical_server_id, key.network_anonymization_key));
1043 }
1044 
RemoveAltSvcCanonicalHost(const url::SchemeHostPort & server,const NetworkAnonymizationKey & network_anonymization_key)1045 void HttpServerProperties::RemoveAltSvcCanonicalHost(
1046     const url::SchemeHostPort& server,
1047     const NetworkAnonymizationKey& network_anonymization_key) {
1048   auto canonical = GetCanonicalAltSvcHost(server, network_anonymization_key);
1049   if (canonical == canonical_alt_svc_map_.end())
1050     return;
1051 
1052   canonical_alt_svc_map_.erase(canonical->first);
1053 }
1054 
UpdateCanonicalServerInfoMap(const QuicServerInfoMapKey & key)1055 void HttpServerProperties::UpdateCanonicalServerInfoMap(
1056     const QuicServerInfoMapKey& key) {
1057   const std::string* suffix = GetCanonicalSuffix(key.server_id.host());
1058   if (!suffix)
1059     return;
1060   quic::QuicServerId canonical_server(
1061       *suffix, key.server_id.privacy_mode_enabled(), key.server_id.port());
1062 
1063   canonical_server_info_map_[CreateQuicServerInfoKey(
1064       canonical_server, key.network_anonymization_key)] = key.server_id;
1065 }
1066 
GetCanonicalSuffix(const std::string & host) const1067 const std::string* HttpServerProperties::GetCanonicalSuffix(
1068     const std::string& host) const {
1069   // If this host ends with a canonical suffix, then return the canonical
1070   // suffix.
1071   for (const std::string& canonical_suffix : canonical_suffixes_) {
1072     if (base::EndsWith(host, canonical_suffix,
1073                        base::CompareCase::INSENSITIVE_ASCII)) {
1074       return &canonical_suffix;
1075     }
1076   }
1077   return nullptr;
1078 }
1079 
OnPrefsLoaded(std::unique_ptr<ServerInfoMap> server_info_map,const IPAddress & last_local_address_when_quic_worked,std::unique_ptr<QuicServerInfoMap> quic_server_info_map,std::unique_ptr<BrokenAlternativeServiceList> broken_alternative_service_list,std::unique_ptr<RecentlyBrokenAlternativeServices> recently_broken_alternative_services)1080 void HttpServerProperties::OnPrefsLoaded(
1081     std::unique_ptr<ServerInfoMap> server_info_map,
1082     const IPAddress& last_local_address_when_quic_worked,
1083     std::unique_ptr<QuicServerInfoMap> quic_server_info_map,
1084     std::unique_ptr<BrokenAlternativeServiceList>
1085         broken_alternative_service_list,
1086     std::unique_ptr<RecentlyBrokenAlternativeServices>
1087         recently_broken_alternative_services) {
1088   DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
1089 
1090   DCHECK(!is_initialized_);
1091 
1092   // Either all of these are nullptr, or none of them are (except the broken alt
1093   // service fields).
1094   if (server_info_map) {
1095     OnServerInfoLoaded(std::move(server_info_map));
1096     OnLastLocalAddressWhenQuicWorkedLoaded(last_local_address_when_quic_worked);
1097     OnQuicServerInfoMapLoaded(std::move(quic_server_info_map));
1098     if (recently_broken_alternative_services) {
1099       DCHECK(broken_alternative_service_list);
1100       OnBrokenAndRecentlyBrokenAlternativeServicesLoaded(
1101           std::move(broken_alternative_service_list),
1102           std::move(recently_broken_alternative_services));
1103     }
1104   }
1105 
1106   is_initialized_ = true;
1107 
1108   if (queue_write_on_load_) {
1109     // Leaving this as true doesn't actually have any effect, but seems best to
1110     // be safe.
1111     queue_write_on_load_ = false;
1112     MaybeQueueWriteProperties();
1113   }
1114 }
1115 
OnServerInfoLoaded(std::unique_ptr<ServerInfoMap> server_info_map)1116 void HttpServerProperties::OnServerInfoLoaded(
1117     std::unique_ptr<ServerInfoMap> server_info_map) {
1118   DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
1119 
1120   // Perform a simple sanity check on loaded data, when DCHECKs are enabled.
1121 #if DCHECK_IS_ON()
1122   if (!use_network_anonymization_key_) {
1123     for (auto server_info = server_info_map->begin();
1124          server_info != server_info_map->end(); ++server_info) {
1125       DCHECK(server_info->first.network_anonymization_key.IsEmpty());
1126     }
1127   }
1128 #endif  // DCHECK_IS_ON()
1129 
1130   // Swap in the entries from persisted data. This allows the MRU cache to be
1131   // sorted based on the order of the entries in the newer in-memory cache.
1132   server_info_map_.Swap(*server_info_map);
1133 
1134   // Add the entries from the memory cache.
1135   for (auto& [key, server_info] : base::Reversed(*server_info_map)) {
1136     // If there's no corresponding old entry, add the new entry directly.
1137     auto old_entry = server_info_map_.Get(key);
1138     if (old_entry == server_info_map_.end()) {
1139       server_info_map_.Put(key, std::move(server_info));
1140       continue;
1141     }
1142 
1143     // Otherwise, merge the old and new entries. Prefer values from older
1144     // entries.
1145     if (!old_entry->second.supports_spdy.has_value())
1146       old_entry->second.supports_spdy = server_info.supports_spdy;
1147     if (!old_entry->second.alternative_services.has_value())
1148       old_entry->second.alternative_services = server_info.alternative_services;
1149     if (!old_entry->second.server_network_stats.has_value())
1150       old_entry->second.server_network_stats = server_info.server_network_stats;
1151 
1152     // |requires_http11| isn't saved to prefs, so the loaded entry should not
1153     // have it set. Unconditionally copy it from the new entry.
1154     DCHECK(!old_entry->second.requires_http11.has_value());
1155     old_entry->second.requires_http11 = server_info.requires_http11;
1156   }
1157 
1158   // Attempt to find canonical servers. Canonical suffix only apply to HTTPS.
1159   const uint16_t kCanonicalPort = 443;
1160   const char* kCanonicalScheme = "https";
1161   for (const auto& it : server_info_map_) {
1162     if (!it.second.alternative_services ||
1163         it.first.server.scheme() != kCanonicalScheme) {
1164       continue;
1165     }
1166     const std::string* canonical_suffix =
1167         GetCanonicalSuffix(it.first.server.host());
1168     if (!canonical_suffix)
1169       continue;
1170     ServerInfoMapKey key = CreateServerInfoKey(
1171         url::SchemeHostPort(kCanonicalScheme, *canonical_suffix,
1172                             kCanonicalPort),
1173         it.first.network_anonymization_key);
1174     // If we already have a valid canonical server, we're done.
1175     if (base::Contains(canonical_alt_svc_map_, key)) {
1176       auto key_it = server_info_map_.Peek(key);
1177       if (key_it != server_info_map_.end() &&
1178           key_it->second.alternative_services.has_value()) {
1179         continue;
1180       }
1181     }
1182     canonical_alt_svc_map_[key] = it.first.server;
1183   }
1184 }
1185 
OnLastLocalAddressWhenQuicWorkedLoaded(const IPAddress & last_local_address_when_quic_worked)1186 void HttpServerProperties::OnLastLocalAddressWhenQuicWorkedLoaded(
1187     const IPAddress& last_local_address_when_quic_worked) {
1188   last_local_address_when_quic_worked_ = last_local_address_when_quic_worked;
1189 }
1190 
OnQuicServerInfoMapLoaded(std::unique_ptr<QuicServerInfoMap> quic_server_info_map)1191 void HttpServerProperties::OnQuicServerInfoMapLoaded(
1192     std::unique_ptr<QuicServerInfoMap> quic_server_info_map) {
1193   DCHECK_EQ(quic_server_info_map->max_size(), quic_server_info_map_.max_size());
1194 
1195   // Add the entries from persisted data.
1196   quic_server_info_map_.Swap(*quic_server_info_map);
1197 
1198   // Add the entries from the memory cache.
1199   for (const auto& [key, server_info] : base::Reversed(*quic_server_info_map)) {
1200     if (quic_server_info_map_.Get(key) == quic_server_info_map_.end()) {
1201       quic_server_info_map_.Put(key, server_info);
1202     }
1203   }
1204 
1205   // Repopulate |canonical_server_info_map_| to stay in sync with
1206   // |quic_server_info_map_|.
1207   canonical_server_info_map_.clear();
1208   for (const auto& [key, server_info] : base::Reversed(quic_server_info_map_)) {
1209     UpdateCanonicalServerInfoMap(key);
1210   }
1211 }
1212 
OnBrokenAndRecentlyBrokenAlternativeServicesLoaded(std::unique_ptr<BrokenAlternativeServiceList> broken_alternative_service_list,std::unique_ptr<RecentlyBrokenAlternativeServices> recently_broken_alternative_services)1213 void HttpServerProperties::OnBrokenAndRecentlyBrokenAlternativeServicesLoaded(
1214     std::unique_ptr<BrokenAlternativeServiceList>
1215         broken_alternative_service_list,
1216     std::unique_ptr<RecentlyBrokenAlternativeServices>
1217         recently_broken_alternative_services) {
1218   broken_alternative_services_.SetBrokenAndRecentlyBrokenAlternativeServices(
1219       std::move(broken_alternative_service_list),
1220       std::move(recently_broken_alternative_services));
1221 }
1222 
MaybeQueueWriteProperties()1223 void HttpServerProperties::MaybeQueueWriteProperties() {
1224   DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
1225 
1226   if (prefs_update_timer_.IsRunning() || !properties_manager_)
1227     return;
1228 
1229   if (!is_initialized_) {
1230     queue_write_on_load_ = true;
1231     return;
1232   }
1233 
1234   prefs_update_timer_.Start(
1235       FROM_HERE, kUpdatePrefsDelay,
1236       base::BindOnce(&HttpServerProperties::WriteProperties,
1237                      base::Unretained(this), base::OnceClosure()));
1238 }
1239 
WriteProperties(base::OnceClosure callback) const1240 void HttpServerProperties::WriteProperties(base::OnceClosure callback) const {
1241   DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
1242   DCHECK(properties_manager_);
1243 
1244   // |this| shouldn't be waiting to load properties cached to disk when this
1245   // method is invoked, since this method will overwrite any cached properties.
1246   DCHECK(is_initialized_);
1247 
1248   // There shouldn't be a queued update when this is run, since this method
1249   // removes the need for any update to be queued.
1250   DCHECK(!prefs_update_timer_.IsRunning());
1251 
1252   properties_manager_->WriteToPrefs(
1253       server_info_map_,
1254       base::BindRepeating(&HttpServerProperties::GetCanonicalSuffix,
1255                           base::Unretained(this)),
1256       last_local_address_when_quic_worked_, quic_server_info_map_,
1257       broken_alternative_services_.broken_alternative_service_list(),
1258       broken_alternative_services_.recently_broken_alternative_services(),
1259       std::move(callback));
1260 }
1261 
1262 }  // namespace net
1263