xref: /aosp_15_r20/external/cronet/net/http/http_server_properties.h (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
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 #ifndef NET_HTTP_HTTP_SERVER_PROPERTIES_H_
6 #define NET_HTTP_HTTP_SERVER_PROPERTIES_H_
7 
8 #include <stddef.h>
9 #include <stdint.h>
10 
11 #include <map>
12 #include <memory>
13 #include <optional>
14 #include <set>
15 #include <string>
16 #include <tuple>
17 #include <vector>
18 
19 #include "base/containers/lru_cache.h"
20 #include "base/functional/callback.h"
21 #include "base/memory/raw_ptr.h"
22 #include "base/memory/weak_ptr.h"
23 #include "base/threading/thread_checker.h"
24 #include "base/time/time.h"
25 #include "base/timer/timer.h"
26 #include "base/values.h"
27 #include "net/base/host_port_pair.h"
28 #include "net/base/ip_address.h"
29 #include "net/base/net_export.h"
30 #include "net/base/network_anonymization_key.h"
31 #include "net/http/alternative_service.h"
32 #include "net/http/broken_alternative_services.h"
33 #include "net/third_party/quiche/src/quiche/quic/core/quic_bandwidth.h"
34 #include "net/third_party/quiche/src/quiche/quic/core/quic_server_id.h"
35 #include "net/third_party/quiche/src/quiche/quic/core/quic_versions.h"
36 #include "net/third_party/quiche/src/quiche/spdy/core/spdy_framer.h"  // TODO(willchan): Reconsider this.
37 #include "net/third_party/quiche/src/quiche/spdy/core/spdy_protocol.h"
38 #include "url/scheme_host_port.h"
39 
40 namespace base {
41 class Clock;
42 class TickClock;
43 }
44 
45 namespace net {
46 
47 class HttpServerPropertiesManager;
48 class IPAddress;
49 class NetLog;
50 struct SSLConfig;
51 
52 struct NET_EXPORT SupportsQuic {
SupportsQuicSupportsQuic53   SupportsQuic() : used_quic(false) {}
SupportsQuicSupportsQuic54   SupportsQuic(bool used_quic, const std::string& address)
55       : used_quic(used_quic), address(address) {}
56 
EqualsSupportsQuic57   bool Equals(const SupportsQuic& other) const {
58     return used_quic == other.used_quic && address == other.address;
59   }
60 
61   bool used_quic;
62   std::string address;
63 };
64 
65 struct NET_EXPORT ServerNetworkStats {
ServerNetworkStatsServerNetworkStats66   ServerNetworkStats() : bandwidth_estimate(quic::QuicBandwidth::Zero()) {}
67 
68   bool operator==(const ServerNetworkStats& other) const {
69     return srtt == other.srtt && bandwidth_estimate == other.bandwidth_estimate;
70   }
71 
72   bool operator!=(const ServerNetworkStats& other) const {
73     return !this->operator==(other);
74   }
75 
76   base::TimeDelta srtt;
77   quic::QuicBandwidth bandwidth_estimate;
78 };
79 
80 typedef std::vector<AlternativeService> AlternativeServiceVector;
81 
82 // Store at most 200 MRU RecentlyBrokenAlternativeServices in memory and disk.
83 // This ideally would be with the other constants in HttpServerProperties, but
84 // has to go here instead of prevent a circular dependency.
85 const int kMaxRecentlyBrokenAlternativeServiceEntries = 200;
86 
87 // Store at most 5 MRU QUIC servers by default. This is mainly used by cronet.
88 const int kDefaultMaxQuicServerEntries = 5;
89 
90 // The interface for setting/retrieving the HTTP server properties.
91 // Currently, this class manages servers':
92 // * HTTP/2 support;
93 // * Alternative Service support;
94 // * QUIC data (like ServerNetworkStats and QuicServerInfo).
95 //
96 // Optionally retrieves and saves properties from/to disk. This class is not
97 // threadsafe.
98 class NET_EXPORT HttpServerProperties
99     : public BrokenAlternativeServices::Delegate {
100  public:
101   // Store at most 500 MRU ServerInfos in memory and disk.
102   static const int kMaxServerInfoEntries = 500;
103 
104   // Provides an interface to interact with persistent preferences storage
105   // implemented by the embedder. The prefs are assumed not to have been loaded
106   // before HttpServerPropertiesManager construction.
107   class NET_EXPORT PrefDelegate {
108    public:
109     virtual ~PrefDelegate();
110 
111     // Returns the branch of the preferences system for the server properties.
112     // Returns nullptr if the pref system has no data for the server properties.
113     virtual const base::Value::Dict& GetServerProperties() const = 0;
114 
115     // Sets the server properties to the given value. If |callback| is
116     // non-empty, flushes data to persistent storage and invokes |callback|
117     // asynchronously when complete.
118     virtual void SetServerProperties(base::Value::Dict dict,
119                                      base::OnceClosure callback) = 0;
120 
121     // Starts listening for prefs to be loaded. If prefs are already loaded,
122     // |pref_loaded_callback| will be invoked asynchronously. Callback will be
123     // invoked even if prefs fail to load. Will only be called once by the
124     // HttpServerPropertiesManager.
125     virtual void WaitForPrefLoad(base::OnceClosure pref_loaded_callback) = 0;
126   };
127 
128   // Contains metadata about a particular server. Note that all methods that
129   // take a "SchemeHostPort" expect schemes of ws and wss to be mapped to http
130   // and https, respectively. See GetNormalizedSchemeHostPort().
131   struct NET_EXPORT ServerInfo {
132     ServerInfo();
133     ServerInfo(const ServerInfo& server_info);
134     ServerInfo(ServerInfo&& server_info);
135     ~ServerInfo();
136 
137     // Returns true if no fields are populated.
138     bool empty() const;
139 
140     // Used in tests.
141     bool operator==(const ServerInfo& other) const;
142 
143     // IMPORTANT:  When adding a field here, be sure to update
144     // HttpServerProperties::OnServerInfoLoaded() as well as
145     // HttpServerPropertiesManager to correctly load/save the from/to the pref
146     // store.
147 
148     // Whether or not a server is known to support H2/SPDY. False indicates
149     // known lack of support, true indicates known support, and not set
150     // indicates unknown. The difference between false and not set only matters
151     // when loading from disk, when an initialized false value will take
152     // priority over a not set value.
153     std::optional<bool> supports_spdy;
154 
155     // True if the server has previously indicated it required HTTP/1.1. Unlike
156     // other fields, not persisted to disk.
157     std::optional<bool> requires_http11;
158 
159     std::optional<AlternativeServiceInfoVector> alternative_services;
160     std::optional<ServerNetworkStats> server_network_stats;
161   };
162 
163   struct NET_EXPORT ServerInfoMapKey {
164     // If |use_network_anonymization_key| is false, an empty
165     // NetworkAnonymizationKey is used instead of |network_anonymization_key|.
166     // Note that |server| can be passed in via std::move(), since most callsites
167     // can pass a recently created SchemeHostPort.
168     ServerInfoMapKey(url::SchemeHostPort server,
169                      const NetworkAnonymizationKey& network_anonymization_key,
170                      bool use_network_anonymization_key);
171     ~ServerInfoMapKey();
172 
173     bool operator<(const ServerInfoMapKey& other) const;
174 
175     // IMPORTANT: The constructor normalizes the scheme so that "ws" is replaced
176     // by "http" and "wss" by "https", so this should never be compared directly
177     // with values passed into to HttpServerProperties methods.
178     url::SchemeHostPort server;
179 
180     NetworkAnonymizationKey network_anonymization_key;
181   };
182 
183   class NET_EXPORT ServerInfoMap
184       : public base::LRUCache<ServerInfoMapKey, ServerInfo> {
185    public:
186     ServerInfoMap();
187 
188     ServerInfoMap(const ServerInfoMap&) = delete;
189     ServerInfoMap& operator=(const ServerInfoMap&) = delete;
190 
191     // If there's an entry corresponding to |key|, brings that entry to the
192     // front and returns an iterator to it. Otherwise, inserts an empty
193     // ServerInfo using |key|, and returns an iterator to it.
194     iterator GetOrPut(const ServerInfoMapKey& key);
195 
196     // Erases the ServerInfo identified by |server_info_it| if no fields have
197     // data. The iterator must point to an entry in the map. Regardless of
198     // whether the entry is removed or not, returns iterator for the next entry.
199     iterator EraseIfEmpty(iterator server_info_it);
200   };
201 
202   struct NET_EXPORT QuicServerInfoMapKey {
203     // If |use_network_anonymization_key| is false, an empty
204     // NetworkAnonymizationKey is used instead of |network_anonymization_key|.
205     QuicServerInfoMapKey(
206         const quic::QuicServerId& server_id,
207         const NetworkAnonymizationKey& network_anonymization_key,
208         bool use_network_anonymization_key);
209     ~QuicServerInfoMapKey();
210 
211     bool operator<(const QuicServerInfoMapKey& other) const;
212 
213     // Used in tests.
214     bool operator==(const QuicServerInfoMapKey& other) const;
215 
216     quic::QuicServerId server_id;
217     NetworkAnonymizationKey network_anonymization_key;
218   };
219 
220   // Max number of quic servers to store is not hardcoded and can be set.
221   // Because of this, QuicServerInfoMap will not be a subclass of LRUCache.
222   // Separate from ServerInfoMap because the key includes privacy mode (Since
223   // this is analogous to the SSL session cache, which has separate caches for
224   // privacy mode), and each entry can be quite large, so it has its own size
225   // limit, which is much smaller than the ServerInfoMap's limit.
226   typedef base::LRUCache<QuicServerInfoMapKey, std::string> QuicServerInfoMap;
227 
228   // If a |pref_delegate| is specified, it will be used to read/write the
229   // properties to a pref file. Writes are rate limited to improve performance.
230   //
231   // |tick_clock| is used for setting expiration times and scheduling the
232   // expiration of broken alternative services. If null, default clock will be
233   // used.
234   //
235   // |clock| is used for converting base::TimeTicks to base::Time for
236   // wherever base::Time is preferable.
237   explicit HttpServerProperties(
238       std::unique_ptr<PrefDelegate> pref_delegate = nullptr,
239       NetLog* net_log = nullptr,
240       const base::TickClock* tick_clock = nullptr,
241       base::Clock* clock = nullptr);
242 
243   HttpServerProperties(const HttpServerProperties&) = delete;
244   HttpServerProperties& operator=(const HttpServerProperties&) = delete;
245 
246   ~HttpServerProperties() override;
247 
248   // Deletes all data. If |callback| is non-null, flushes data to disk
249   // and invokes the callback asynchronously once changes have been written to
250   // disk.
251   void Clear(base::OnceClosure callback);
252 
253   // Returns true if |server|, in the context of |network_anonymization_key|,
254   // has previously supported a network protocol which honors request
255   // prioritization.
256   //
257   // Note that this also implies that the server supports request
258   // multiplexing, since priorities imply a relationship between
259   // multiple requests.
260   bool SupportsRequestPriority(
261       const url::SchemeHostPort& server,
262       const net::NetworkAnonymizationKey& network_anonymization_key);
263 
264   // Returns the value set by SetSupportsSpdy(). If not set, returns false.
265   bool GetSupportsSpdy(
266       const url::SchemeHostPort& server,
267       const net::NetworkAnonymizationKey& network_anonymization_key);
268 
269   // Records whether |server| supports H2 or not. Information is restricted to
270   // the context of |network_anonymization_key|, to prevent cross-site
271   // information leakage.
272   void SetSupportsSpdy(
273       const url::SchemeHostPort& server,
274       const net::NetworkAnonymizationKey& network_anonymization_key,
275       bool supports_spdy);
276 
277   // Returns true if |server| has required HTTP/1.1 via HTTP/2 error code, in
278   // the context of |network_anonymization_key|.
279   //
280   // Any relevant HostMappingRules must already have been applied to `server`.
281   bool RequiresHTTP11(
282       const url::SchemeHostPort& server,
283       const net::NetworkAnonymizationKey& network_anonymization_key);
284 
285   // Require HTTP/1.1 on subsequent connections, in the context of
286   // |network_anonymization_key|.  Not persisted.
287   //
288   // Any relevant HostMappingRules must already have been applied to `server`.
289   void SetHTTP11Required(
290       const url::SchemeHostPort& server,
291       const net::NetworkAnonymizationKey& network_anonymization_key);
292 
293   // Modify SSLConfig to force HTTP/1.1 if necessary.
294   //
295   // Any relevant HostMappingRules must already have been applied to `server`.
296   void MaybeForceHTTP11(
297       const url::SchemeHostPort& server,
298       const net::NetworkAnonymizationKey& network_anonymization_key,
299       SSLConfig* ssl_config);
300 
301   // Return all alternative services for |origin|, learned in the context of
302   // |network_anonymization_key|, including broken ones. Returned alternative
303   // services never have empty hostnames.
304   AlternativeServiceInfoVector GetAlternativeServiceInfos(
305       const url::SchemeHostPort& origin,
306       const net::NetworkAnonymizationKey& network_anonymization_key);
307 
308   // Set a single HTTP/2 alternative service for |origin|.  Previous
309   // alternative services for |origin| are discarded.
310   // |alternative_service.host| may be empty.
311   void SetHttp2AlternativeService(
312       const url::SchemeHostPort& origin,
313       const NetworkAnonymizationKey& network_anonymization_key,
314       const AlternativeService& alternative_service,
315       base::Time expiration);
316 
317   // Set a single QUIC alternative service for |origin|.  Previous alternative
318   // services for |origin| are discarded.
319   // |alternative_service.host| may be empty.
320   void SetQuicAlternativeService(
321       const url::SchemeHostPort& origin,
322       const NetworkAnonymizationKey& network_anonymization_key,
323       const AlternativeService& alternative_service,
324       base::Time expiration,
325       const quic::ParsedQuicVersionVector& advertised_versions);
326 
327   // Set alternative services for |origin|, learned in the context of
328   // |network_anonymization_key|.  Previous alternative services for |origin|
329   // are discarded. Hostnames in |alternative_service_info_vector| may be empty.
330   // |alternative_service_info_vector| may be empty.
331   void SetAlternativeServices(
332       const url::SchemeHostPort& origin,
333       const net::NetworkAnonymizationKey& network_anonymization_key,
334       const AlternativeServiceInfoVector& alternative_service_info_vector);
335 
336   // Marks |alternative_service| as broken in the context of
337   // |network_anonymization_key|. |alternative_service.host| must not be empty.
338   void MarkAlternativeServiceBroken(
339       const AlternativeService& alternative_service,
340       const net::NetworkAnonymizationKey& network_anonymization_key);
341 
342   // Marks |alternative_service| as broken in the context of
343   // |network_anonymization_key| until the default network changes.
344   // |alternative_service.host| must not be empty.
345   void MarkAlternativeServiceBrokenUntilDefaultNetworkChanges(
346       const AlternativeService& alternative_service,
347       const net::NetworkAnonymizationKey& network_anonymization_key);
348 
349   // Marks |alternative_service| as recently broken in the context of
350   // |network_anonymization_key|. |alternative_service.host| must not be empty.
351   void MarkAlternativeServiceRecentlyBroken(
352       const AlternativeService& alternative_service,
353       const net::NetworkAnonymizationKey& network_anonymization_key);
354 
355   // Returns true iff |alternative_service| is currently broken in the context
356   // of |network_anonymization_key|. |alternative_service.host| must not be
357   // empty.
358   bool IsAlternativeServiceBroken(
359       const AlternativeService& alternative_service,
360       const net::NetworkAnonymizationKey& network_anonymization_key) const;
361 
362   // Returns true iff |alternative_service| was recently broken in the context
363   // of |network_anonymization_key|. |alternative_service.host| must not be
364   // empty.
365   bool WasAlternativeServiceRecentlyBroken(
366       const AlternativeService& alternative_service,
367       const net::NetworkAnonymizationKey& network_anonymization_key);
368 
369   // Confirms that |alternative_service| is working in the context of
370   // |network_anonymization_key|. |alternative_service.host| must not be empty.
371   void ConfirmAlternativeService(
372       const AlternativeService& alternative_service,
373       const net::NetworkAnonymizationKey& network_anonymization_key);
374 
375   // Called when the default network changes.
376   // Clears all the alternative services that were marked broken until the
377   // default network changed.
378   void OnDefaultNetworkChanged();
379 
380   // Returns all alternative service mappings as human readable strings.
381   // Empty alternative service hostnames will be printed as such.
382   base::Value GetAlternativeServiceInfoAsValue() const;
383 
384   // Tracks the last local address when QUIC was known to work. The address
385   // cannot be set to an empty address - use
386   // ClearLastLocalAddressWhenQuicWorked() if it needs to be cleared.
387   bool WasLastLocalAddressWhenQuicWorked(const IPAddress& local_address) const;
388   bool HasLastLocalAddressWhenQuicWorked() const;
389   void SetLastLocalAddressWhenQuicWorked(
390       IPAddress last_local_address_when_quic_worked);
391   void ClearLastLocalAddressWhenQuicWorked();
392 
393   // Sets |stats| for |server|.
394   void SetServerNetworkStats(
395       const url::SchemeHostPort& server,
396       const NetworkAnonymizationKey& network_anonymization_key,
397       ServerNetworkStats stats);
398 
399   // Clears any stats for |server|.
400   void ClearServerNetworkStats(
401       const url::SchemeHostPort& server,
402       const NetworkAnonymizationKey& network_anonymization_key);
403 
404   // Returns any stats for |server| or nullptr if there are none.
405   const ServerNetworkStats* GetServerNetworkStats(
406       const url::SchemeHostPort& server,
407       const NetworkAnonymizationKey& network_anonymization_key);
408 
409   // Save QuicServerInfo (in std::string form) for the given |server_id|, in the
410   // context of |network_anonymization_key|.
411   void SetQuicServerInfo(
412       const quic::QuicServerId& server_id,
413       const NetworkAnonymizationKey& network_anonymization_key,
414       const std::string& server_info);
415 
416   // Get QuicServerInfo (in std::string form) for the given |server_id|, in the
417   // context of |network_anonymization_key|.
418   const std::string* GetQuicServerInfo(
419       const quic::QuicServerId& server_id,
420       const NetworkAnonymizationKey& network_anonymization_key);
421 
422   // Returns all persistent QuicServerInfo objects.
423   const QuicServerInfoMap& quic_server_info_map() const;
424 
425   // Returns the number of server configs (QuicServerInfo objects) persisted.
426   size_t max_server_configs_stored_in_properties() const;
427 
428   // Sets the number of server configs (QuicServerInfo objects) to be persisted.
429   void SetMaxServerConfigsStoredInProperties(
430       size_t max_server_configs_stored_in_properties);
431 
432   // If values are present, sets initial_delay and
433   // exponential_backoff_on_initial_delay which are used to calculate delay of
434   // broken alternative services.
435   void SetBrokenAlternativeServicesDelayParams(
436       std::optional<base::TimeDelta> initial_delay,
437       std::optional<bool> exponential_backoff_on_initial_delay);
438 
439   // Returns whether HttpServerProperties is initialized.
440   bool IsInitialized() const;
441 
442   // BrokenAlternativeServices::Delegate method.
443   void OnExpireBrokenAlternativeService(
444       const AlternativeService& expired_alternative_service,
445       const NetworkAnonymizationKey& network_anonymization_key) override;
446 
447   static base::TimeDelta GetUpdatePrefsDelayForTesting();
448 
449   // Test-only routines that call the methods used to load the specified
450   // field(s) from a prefs file. Unlike OnPrefsLoaded(), these may be invoked
451   // multiple times.
OnServerInfoLoadedForTesting(std::unique_ptr<ServerInfoMap> server_info_map)452   void OnServerInfoLoadedForTesting(
453       std::unique_ptr<ServerInfoMap> server_info_map) {
454     OnServerInfoLoaded(std::move(server_info_map));
455   }
OnLastLocalAddressWhenQuicWorkedForTesting(const IPAddress & last_local_address_when_quic_worked)456   void OnLastLocalAddressWhenQuicWorkedForTesting(
457       const IPAddress& last_local_address_when_quic_worked) {
458     OnLastLocalAddressWhenQuicWorkedLoaded(last_local_address_when_quic_worked);
459   }
OnQuicServerInfoMapLoadedForTesting(std::unique_ptr<QuicServerInfoMap> quic_server_info_map)460   void OnQuicServerInfoMapLoadedForTesting(
461       std::unique_ptr<QuicServerInfoMap> quic_server_info_map) {
462     OnQuicServerInfoMapLoaded(std::move(quic_server_info_map));
463   }
OnBrokenAndRecentlyBrokenAlternativeServicesLoadedForTesting(std::unique_ptr<BrokenAlternativeServiceList> broken_alternative_service_list,std::unique_ptr<RecentlyBrokenAlternativeServices> recently_broken_alternative_services)464   void OnBrokenAndRecentlyBrokenAlternativeServicesLoadedForTesting(
465       std::unique_ptr<BrokenAlternativeServiceList>
466           broken_alternative_service_list,
467       std::unique_ptr<RecentlyBrokenAlternativeServices>
468           recently_broken_alternative_services) {
469     OnBrokenAndRecentlyBrokenAlternativeServicesLoaded(
470         std::move(broken_alternative_service_list),
471         std::move(recently_broken_alternative_services));
472   }
473 
GetCanonicalSuffixForTesting(const std::string & host)474   const std::string* GetCanonicalSuffixForTesting(
475       const std::string& host) const {
476     return GetCanonicalSuffix(host);
477   }
478 
server_info_map_for_testing()479   const ServerInfoMap& server_info_map_for_testing() const {
480     return server_info_map_;
481   }
482 
483   // This will invalidate the start-up properties if called before
484   // initialization.
485   void FlushWritePropertiesForTesting(base::OnceClosure callback);
486 
broken_alternative_services_for_testing()487   const BrokenAlternativeServices& broken_alternative_services_for_testing()
488       const {
489     return broken_alternative_services_;
490   }
491 
quic_server_info_map_for_testing()492   const QuicServerInfoMap& quic_server_info_map_for_testing() const {
493     return quic_server_info_map_;
494   }
495 
496   // TODO(mmenke): Look into removing this.
properties_manager_for_testing()497   HttpServerPropertiesManager* properties_manager_for_testing() {
498     return properties_manager_.get();
499   }
500 
501  private:
502   // TODO (wangyix): modify HttpServerProperties unit tests so this
503   // friendness is no longer required.
504   friend class HttpServerPropertiesPeer;
505 
506   typedef base::flat_map<ServerInfoMapKey, url::SchemeHostPort> CanonicalMap;
507   typedef base::flat_map<QuicServerInfoMapKey, quic::QuicServerId>
508       QuicCanonicalMap;
509   typedef std::vector<std::string> CanonicalSuffixList;
510 
511   // Internal implementations of public methods. SchemeHostPort argument must be
512   // normalized before calling (ws/wss replaced with http/https). Use wrapped
513   // functions instead of putting the normalization in the public functions to
514   // reduce chance of regression - normalization in ServerInfoMapKey's
515   // constructor would leave |server.scheme| as wrong if not access through the
516   // key, and explicit normalization to create |normalized_server| means the one
517   // with the incorrect scheme would still be available.
518   bool GetSupportsSpdyInternal(
519       url::SchemeHostPort server,
520       const net::NetworkAnonymizationKey& network_anonymization_key);
521   void SetSupportsSpdyInternal(
522       url::SchemeHostPort server,
523       const net::NetworkAnonymizationKey& network_anonymization_key,
524       bool supports_spdy);
525   bool RequiresHTTP11Internal(
526       url::SchemeHostPort server,
527       const net::NetworkAnonymizationKey& network_anonymization_key);
528   void SetHTTP11RequiredInternal(
529       url::SchemeHostPort server,
530       const net::NetworkAnonymizationKey& network_anonymization_key);
531   void MaybeForceHTTP11Internal(
532       url::SchemeHostPort server,
533       const net::NetworkAnonymizationKey& network_anonymization_key,
534       SSLConfig* ssl_config);
535   AlternativeServiceInfoVector GetAlternativeServiceInfosInternal(
536       const url::SchemeHostPort& origin,
537       const net::NetworkAnonymizationKey& network_anonymization_key);
538   void SetAlternativeServicesInternal(
539       const url::SchemeHostPort& origin,
540       const net::NetworkAnonymizationKey& network_anonymization_key,
541       const AlternativeServiceInfoVector& alternative_service_info_vector);
542   void SetServerNetworkStatsInternal(
543       url::SchemeHostPort server,
544       const NetworkAnonymizationKey& network_anonymization_key,
545       ServerNetworkStats stats);
546   void ClearServerNetworkStatsInternal(
547       url::SchemeHostPort server,
548       const NetworkAnonymizationKey& network_anonymization_key);
549   const ServerNetworkStats* GetServerNetworkStatsInternal(
550       url::SchemeHostPort server,
551       const NetworkAnonymizationKey& network_anonymization_key);
552 
553   // Helper functions to use the passed in parameters and
554   // |use_network_anonymization_key_| to create a [Quic]ServerInfoMapKey.
555   ServerInfoMapKey CreateServerInfoKey(
556       const url::SchemeHostPort& server,
557       const NetworkAnonymizationKey& network_anonymization_key) const;
558   QuicServerInfoMapKey CreateQuicServerInfoKey(
559       const quic::QuicServerId& server_id,
560       const NetworkAnonymizationKey& network_anonymization_key) const;
561 
562   // Return the iterator for |server| in the context of
563   // |network_anonymization_key|, or for its canonical host, or end. Skips over
564   // ServerInfos without |alternative_service_info| populated.
565   ServerInfoMap::const_iterator GetIteratorWithAlternativeServiceInfo(
566       const url::SchemeHostPort& server,
567       const net::NetworkAnonymizationKey& network_anonymization_key);
568 
569   // Return the canonical host for |server|  in the context of
570   // |network_anonymization_key|, or end if none exists.
571   CanonicalMap::const_iterator GetCanonicalAltSvcHost(
572       const url::SchemeHostPort& server,
573       const net::NetworkAnonymizationKey& network_anonymization_key) const;
574 
575   // Return the canonical host with the same canonical suffix as |server|.
576   // The returned canonical host can be used to search for server info in
577   // |quic_server_info_map_|. Return 'end' the host doesn't exist.
578   QuicCanonicalMap::const_iterator GetCanonicalServerInfoHost(
579       const QuicServerInfoMapKey& key) const;
580 
581   // Remove the canonical alt-svc host for |server| with
582   // |network_anonymization_key|.
583   void RemoveAltSvcCanonicalHost(
584       const url::SchemeHostPort& server,
585       const NetworkAnonymizationKey& network_anonymization_key);
586 
587   // Update |canonical_server_info_map_| with the new canonical host.
588   // The |key| should have the corresponding server info associated with it
589   // in |quic_server_info_map_|. If |canonical_server_info_map_| doesn't
590   // have an entry associated with |key|, the method will add one.
591   void UpdateCanonicalServerInfoMap(const QuicServerInfoMapKey& key);
592 
593   // Returns the canonical host suffix for |host|, or nullptr if none
594   // exists.
595   const std::string* GetCanonicalSuffix(const std::string& host) const;
596 
597   void OnPrefsLoaded(std::unique_ptr<ServerInfoMap> server_info_map,
598                      const IPAddress& last_local_address_when_quic_worked,
599                      std::unique_ptr<QuicServerInfoMap> quic_server_info_map,
600                      std::unique_ptr<BrokenAlternativeServiceList>
601                          broken_alternative_service_list,
602                      std::unique_ptr<RecentlyBrokenAlternativeServices>
603                          recently_broken_alternative_services);
604 
605   // These methods are called by OnPrefsLoaded to handle merging properties
606   // loaded from prefs with what has been learned while waiting for prefs to
607   // load.
608   void OnServerInfoLoaded(std::unique_ptr<ServerInfoMap> server_info_map);
609   void OnLastLocalAddressWhenQuicWorkedLoaded(
610       const IPAddress& last_local_address_when_quic_worked);
611   void OnQuicServerInfoMapLoaded(
612       std::unique_ptr<QuicServerInfoMap> quic_server_info_map);
613   void OnBrokenAndRecentlyBrokenAlternativeServicesLoaded(
614       std::unique_ptr<BrokenAlternativeServiceList>
615           broken_alternative_service_list,
616       std::unique_ptr<RecentlyBrokenAlternativeServices>
617           recently_broken_alternative_services);
618 
619   // Queue a delayed call to WriteProperties(). If |is_initialized_| is false,
620   // or |properties_manager_| is nullptr, or there's already a queued call to
621   // WriteProperties(), does nothing.
622   void MaybeQueueWriteProperties();
623 
624   // Writes cached state to |properties_manager_|, which must not be null.
625   // Invokes |callback| on completion, if non-null.
626   void WriteProperties(base::OnceClosure callback) const;
627 
628   raw_ptr<const base::TickClock> tick_clock_;  // Unowned
629   raw_ptr<base::Clock> clock_;                 // Unowned
630 
631   // Cached value of whether network state partitioning is enabled. Cached to
632   // improve performance.
633   const bool use_network_anonymization_key_;
634 
635   // Set to true once initial properties have been retrieved from disk by
636   // |properties_manager_|. Always true if |properties_manager_| is nullptr.
637   bool is_initialized_;
638 
639   // Queue a write when resources finish loading. Set to true when
640   // MaybeQueueWriteProperties() is invoked while still waiting on
641   // initialization to complete.
642   bool queue_write_on_load_ = false;
643 
644   // Used to load/save properties from/to preferences. May be nullptr.
645   std::unique_ptr<HttpServerPropertiesManager> properties_manager_;
646 
647   ServerInfoMap server_info_map_;
648 
649   BrokenAlternativeServices broken_alternative_services_;
650 
651   IPAddress last_local_address_when_quic_worked_;
652   // Contains a map of servers which could share the same alternate protocol.
653   // Map from a Canonical scheme/host/port/NAK (host is some postfix of host
654   // names) to an actual origin, which has a plausible alternate protocol
655   // mapping.
656   CanonicalMap canonical_alt_svc_map_;
657 
658   // Contains list of suffixes (for example ".c.youtube.com",
659   // ".googlevideo.com", ".googleusercontent.com") of canonical hostnames.
660   const CanonicalSuffixList canonical_suffixes_;
661 
662   QuicServerInfoMap quic_server_info_map_;
663 
664   // Maps canonical suffixes to host names that have the same canonical suffix
665   // and have a corresponding entry in |quic_server_info_map_|. The map can be
666   // used to quickly look for server info for hosts that share the same
667   // canonical suffix but don't have exact match in |quic_server_info_map_|. The
668   // map exists solely to improve the search performance. It only contains
669   // derived data that can be recalculated by traversing
670   // |quic_server_info_map_|.
671   QuicCanonicalMap canonical_server_info_map_;
672 
673   size_t max_server_configs_stored_in_properties_;
674 
675   // Used to post calls to WriteProperties().
676   base::OneShotTimer prefs_update_timer_;
677 
678   THREAD_CHECKER(thread_checker_);
679 };
680 
681 }  // namespace net
682 
683 #endif  // NET_HTTP_HTTP_SERVER_PROPERTIES_H_
684