xref: /aosp_15_r20/external/cronet/net/http/http_server_properties_manager.h (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
1 // Copyright 2014 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_MANAGER_H_
6 #define NET_HTTP_HTTP_SERVER_PROPERTIES_MANAGER_H_
7 
8 #include <memory>
9 #include <string>
10 
11 #include "base/functional/callback.h"
12 #include "base/gtest_prod_util.h"
13 #include "base/memory/raw_ptr.h"
14 #include "base/memory/weak_ptr.h"
15 #include "base/sequence_checker.h"
16 #include "net/base/host_port_pair.h"
17 #include "net/base/net_export.h"
18 #include "net/http/alternative_service.h"
19 #include "net/http/broken_alternative_services.h"
20 #include "net/http/http_server_properties.h"
21 #include "net/log/net_log_with_source.h"
22 
23 namespace base {
24 class TickClock;
25 }
26 
27 namespace net {
28 
29 class IPAddress;
30 
31 ////////////////////////////////////////////////////////////////////////////////
32 // HttpServerPropertiesManager
33 
34 // Class responsible for serializing/deserializing HttpServerProperties and
35 // reading from/writing to preferences.
36 class NET_EXPORT_PRIVATE HttpServerPropertiesManager {
37  public:
38   // Called when prefs are loaded. If prefs completely failed to load,
39   // everything will be nullptr. Otherwise, everything will be populated, except
40   // |broken_alternative_service_list| and
41   // |recently_broken_alternative_services|, which may be null.
42   using OnPrefsLoadedCallback = base::OnceCallback<void(
43       std::unique_ptr<HttpServerProperties::ServerInfoMap> server_info_map,
44       const IPAddress& last_local_address_when_quic_worked,
45       std::unique_ptr<HttpServerProperties::QuicServerInfoMap>
46           quic_server_info_map,
47       std::unique_ptr<BrokenAlternativeServiceList>
48           broken_alternative_service_list,
49       std::unique_ptr<RecentlyBrokenAlternativeServices>
50           recently_broken_alternative_services)>;
51 
52   using GetCannonicalSuffix =
53       base::RepeatingCallback<const std::string*(const std::string& host)>;
54 
55   // Create an instance of the HttpServerPropertiesManager.
56   //
57   // |on_prefs_loaded_callback| will be invoked with values loaded from
58   // |prefs_delegate| once prefs have been loaded from disk.
59   // If WriteToPrefs() is invoked before this happens,
60   // |on_prefs_loaded_callback| will never be invoked, since the written prefs
61   // take precedence over the ones previously stored on disk.
62   //
63   // |clock| is used for setting expiration times and scheduling the
64   // expiration of broken alternative services, and must not be nullptr.
65   HttpServerPropertiesManager(
66       std::unique_ptr<HttpServerProperties::PrefDelegate> pref_delegate,
67       OnPrefsLoadedCallback on_prefs_loaded_callback,
68       size_t max_server_configs_stored_in_properties,
69       NetLog* net_log,
70       const base::TickClock* clock = nullptr);
71 
72   HttpServerPropertiesManager(const HttpServerPropertiesManager&) = delete;
73   HttpServerPropertiesManager& operator=(const HttpServerPropertiesManager&) =
74       delete;
75 
76   ~HttpServerPropertiesManager();
77 
78   // Populates passed in objects with data from preferences. If pref data is not
79   // present, leaves all values alone. Otherwise, populates them all, with the
80   // possible exception of the two broken alt services lists.
81   //
82   // Corrupted data is ignored.
83   //
84   // TODO(mmenke): Consider always populating fields, unconditionally, for a
85   // simpler API.
86   void ReadPrefs(
87       std::unique_ptr<HttpServerProperties::ServerInfoMap>* server_info_map,
88       IPAddress* last_local_address_when_quic_worked,
89       std::unique_ptr<HttpServerProperties::QuicServerInfoMap>*
90           quic_server_info_map,
91       std::unique_ptr<BrokenAlternativeServiceList>*
92           broken_alternative_service_list,
93       std::unique_ptr<RecentlyBrokenAlternativeServices>*
94           recently_broken_alternative_services);
95 
set_max_server_configs_stored_in_properties(size_t max_server_configs_stored_in_properties)96   void set_max_server_configs_stored_in_properties(
97       size_t max_server_configs_stored_in_properties) {
98     max_server_configs_stored_in_properties_ =
99         max_server_configs_stored_in_properties;
100   }
101 
102   // Update preferences with caller-provided data. Invokes |callback| when
103   // changes have been committed, if non-null.
104   //
105   // If the OnPrefLoadCallback() passed to the constructor hasn't been invoked
106   // by the time this method is called, calling this will prevent it from ever
107   // being invoked, as this method will overwrite any previous preferences.
108   //
109   // Entries associated with NetworkAnonymizationKeys for opaque origins are not
110   // written to disk.
111   void WriteToPrefs(
112       const HttpServerProperties::ServerInfoMap& server_info_map,
113       const GetCannonicalSuffix& get_canonical_suffix,
114       const IPAddress& last_local_address_when_quic_worked,
115       const HttpServerProperties::QuicServerInfoMap& quic_server_info_map,
116       const BrokenAlternativeServiceList& broken_alternative_service_list,
117       const RecentlyBrokenAlternativeServices&
118           recently_broken_alternative_services,
119       base::OnceClosure callback);
120 
121  private:
122   // TODO(mmenke): Remove these friend methods, and make all methods static that
123   // can be.
124   FRIEND_TEST_ALL_PREFIXES(HttpServerPropertiesManagerTest,
125                            ParseAlternativeServiceInfo);
126   FRIEND_TEST_ALL_PREFIXES(HttpServerPropertiesManagerTest,
127                            ReadAdvertisedVersionsFromPref);
128   FRIEND_TEST_ALL_PREFIXES(HttpServerPropertiesManagerTest,
129                            DoNotLoadAltSvcForInsecureOrigins);
130   FRIEND_TEST_ALL_PREFIXES(HttpServerPropertiesManagerTest,
131                            DoNotLoadExpiredAlternativeService);
132   FRIEND_TEST_ALL_PREFIXES(HttpServerPropertiesManagerTest,
133                            AdvertisedVersionsRoundTrip);
134 
135   void AddServerData(const base::Value::Dict& server_dict,
136                      HttpServerProperties::ServerInfoMap* server_info_map,
137                      bool use_network_anonymization_key);
138 
139   // Helper method used for parsing an alternative service from JSON.
140   // |dict| is the JSON dictionary to be parsed. It should contain fields
141   // corresponding to members of AlternativeService.
142   // |host_optional| determines whether or not the "host" field is optional. If
143   // optional, the default value is empty string.
144   // |parsing_under| is used only for debug log outputs in case of error; it
145   // should describe what section of the JSON prefs is currently being parsed.
146   // |alternative_service| is the output of parsing |dict|.
147   // Return value is true if parsing is successful.
148   static bool ParseAlternativeServiceDict(
149       const base::Value::Dict& dict,
150       bool host_optional,
151       const std::string& parsing_under,
152       AlternativeService* alternative_service);
153 
154   static bool ParseAlternativeServiceInfoDictOfServer(
155       const base::Value::Dict& dict,
156       const std::string& server_str,
157       AlternativeServiceInfo* alternative_service_info);
158 
159   // Attempts to populate |server_info|'s |alternative_service_info| field from
160   // |server_dict|. Returns true if the data was no corrupted (Lack of data is
161   // not considered corruption).
162   static bool ParseAlternativeServiceInfo(
163       const url::SchemeHostPort& server,
164       const base::Value::Dict& server_dict,
165       HttpServerProperties::ServerInfo* server_info);
166 
167   void ReadLastLocalAddressWhenQuicWorked(
168       const base::Value::Dict& server_dict,
169       IPAddress* last_local_address_when_quic_worked);
170   void ParseNetworkStats(const url::SchemeHostPort& server,
171                          const base::Value::Dict& server_dict,
172                          HttpServerProperties::ServerInfo* server_info);
173   void AddToQuicServerInfoMap(
174       const base::Value::Dict& server_dict,
175       bool use_network_anonymization_key,
176       HttpServerProperties::QuicServerInfoMap* quic_server_info_map);
177   void AddToBrokenAlternativeServices(
178       const base::Value::Dict& broken_alt_svc_entry_dict,
179       bool use_network_anonymization_key,
180       BrokenAlternativeServiceList* broken_alternative_service_list,
181       RecentlyBrokenAlternativeServices* recently_broken_alternative_services);
182 
183   void SaveAlternativeServiceToServerPrefs(
184       const AlternativeServiceInfoVector& alternative_service_info_vector,
185       base::Value::Dict& server_pref_dict);
186   void SaveLastLocalAddressWhenQuicWorkedToPrefs(
187       const IPAddress& last_local_address_when_quic_worked,
188       base::Value::Dict& http_server_properties_dict);
189   void SaveNetworkStatsToServerPrefs(
190       const ServerNetworkStats& server_network_stats,
191       base::Value::Dict& server_pref_dict);
192   void SaveQuicServerInfoMapToServerPrefs(
193       const HttpServerProperties::QuicServerInfoMap& quic_server_info_map,
194       base::Value::Dict& http_server_properties_dict);
195   void SaveBrokenAlternativeServicesToPrefs(
196       const BrokenAlternativeServiceList& broken_alternative_service_list,
197       size_t max_broken_alternative_services,
198       const RecentlyBrokenAlternativeServices&
199           recently_broken_alternative_services,
200       base::Value::Dict& http_server_properties_dict);
201 
202   void OnHttpServerPropertiesLoaded();
203 
204   std::unique_ptr<HttpServerProperties::PrefDelegate> pref_delegate_;
205 
206   OnPrefsLoadedCallback on_prefs_loaded_callback_;
207 
208   size_t max_server_configs_stored_in_properties_;
209 
210   raw_ptr<const base::TickClock> clock_;  // Unowned
211 
212   const NetLogWithSource net_log_;
213 
214   SEQUENCE_CHECKER(sequence_checker_);
215 
216   base::WeakPtrFactory<HttpServerPropertiesManager> pref_load_weak_ptr_factory_{
217       this};
218 };
219 
220 }  // namespace net
221 
222 #endif  // NET_HTTP_HTTP_SERVER_PROPERTIES_MANAGER_H_
223