1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
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 CHROMEOS_NETWORK_NETWORK_STATE_HANDLER_H_
6 #define CHROMEOS_NETWORK_NETWORK_STATE_HANDLER_H_
7 
8 #include <map>
9 #include <memory>
10 #include <string>
11 #include <vector>
12 
13 #include "base/callback_forward.h"
14 #include "base/component_export.h"
15 #include "base/gtest_prod_util.h"
16 #include "base/macros.h"
17 #include "base/observer_list.h"
18 #include "base/sequence_checker.h"
19 #include "chromeos/network/managed_state.h"
20 #include "chromeos/network/network_handler.h"
21 #include "chromeos/network/network_handler_callbacks.h"
22 #include "chromeos/network/network_state.h"
23 #include "chromeos/network/network_type_pattern.h"
24 #include "chromeos/network/shill_property_handler.h"
25 
26 namespace base {
27 class ListValue;
28 class Location;
29 class Value;
30 }  // namespace base
31 
32 namespace chromeos {
33 
34 class DeviceState;
35 class NetworkState;
36 class NetworkStateHandlerObserver;
37 class NetworkStateHandlerTest;
38 
39 // Class for tracking the list of visible networks and their properties.
40 //
41 // This class maps essential properties from the connection manager (Shill) for
42 // each visible network. It is not used to change the properties of services or
43 // devices, only global (manager) properties.
44 //
45 // All getters return the currently cached properties. This class is expected to
46 // keep properties up to date by managing the appropriate Shill observers.
47 // It will invoke its own more specific observer methods when the specified
48 // changes occur.
49 //
50 // Some notes about NetworkState and GUIDs:
51 // * A NetworkState exists for all network services stored in a profile, and
52 //   all "visible" networks (physically connected networks like ethernet and
53 //   cellular or in-range wifi networks). If the network is stored in a profile,
54 //   NetworkState.IsInProfile() will return true.
55 // * "Visible" networks return true for NetworkState.visible().
56 // * All networks saved to a profile will have a saved GUID that is persistent
57 //   across sessions.
58 // * Networks that are not saved to a profile will have a GUID assigned when
59 //   the initial properties are received. The GUID will be consistent for
60 //   the duration of a session, even if the network drops out and returns.
61 
COMPONENT_EXPORT(CHROMEOS_NETWORK)62 class COMPONENT_EXPORT(CHROMEOS_NETWORK) NetworkStateHandler
63     : public internal::ShillPropertyHandler::Listener {
64  public:
65   typedef std::vector<std::unique_ptr<ManagedState>> ManagedStateList;
66   typedef std::vector<const NetworkState*> NetworkStateList;
67   typedef std::vector<const DeviceState*> DeviceStateList;
68 
69   class TetherSortDelegate {
70    public:
71     // Sorts |tether_networks| according to the Tether component rules.
72     // |tether_networks| contains only networks of type Tether.
73     virtual void SortTetherNetworkList(
74         ManagedStateList* tether_networks) const = 0;
75   };
76 
77   enum TechnologyState {
78     TECHNOLOGY_UNAVAILABLE,
79     TECHNOLOGY_AVAILABLE,
80     TECHNOLOGY_UNINITIALIZED,
81     TECHNOLOGY_ENABLING,
82     TECHNOLOGY_ENABLED,
83     TECHNOLOGY_DISABLING,
84     TECHNOLOGY_PROHIBITED
85   };
86 
87   ~NetworkStateHandler() override;
88 
89   // Called just before destruction to give observers a chance to remove
90   // themselves and disable any networking.
91   void Shutdown();
92 
93   // Add/remove observers.
94   void AddObserver(NetworkStateHandlerObserver* observer,
95                    const base::Location& from_here);
96   void RemoveObserver(NetworkStateHandlerObserver* observer,
97                       const base::Location& from_here);
98   bool HasObserver(NetworkStateHandlerObserver* observer);
99 
100   // Returns the state for technology |type|. Only
101   // NetworkTypePattern::Primitive, ::Mobile, ::Ethernet, and ::Tether are
102   // supported.
103   TechnologyState GetTechnologyState(const NetworkTypePattern& type) const;
104   bool IsTechnologyAvailable(const NetworkTypePattern& type) const {
105     return GetTechnologyState(type) != TECHNOLOGY_UNAVAILABLE;
106   }
107   bool IsTechnologyEnabled(const NetworkTypePattern& type) const {
108     return GetTechnologyState(type) == TECHNOLOGY_ENABLED;
109   }
110   bool IsTechnologyProhibited(const NetworkTypePattern& type) const {
111     return GetTechnologyState(type) == TECHNOLOGY_PROHIBITED;
112   }
113   bool IsTechnologyUninitialized(const NetworkTypePattern& type) const {
114     return GetTechnologyState(type) == TECHNOLOGY_UNINITIALIZED;
115   }
116 
117   // Asynchronously sets the technology enabled property for |type|. Only
118   // NetworkTypePattern::Primitive, ::Mobile and ::Ethernet are supported.
119   // Note: Modifies Manager state. Calls |error_callback| on failure.
120   void SetTechnologyEnabled(const NetworkTypePattern& type,
121                             bool enabled,
122                             network_handler::ErrorCallback error_callback);
123 
124   // Sets the Tether technology state. Because Tether networks do not represent
125   // real Shill networks, this value must be set by the Tether component rather
126   // than being generated by Shill. See TetherDeviceStateManager for more
127   // details.
128   void SetTetherTechnologyState(TechnologyState technology_state);
129 
130   // Sets the scanning state of the Tether technology. Since Tether network
131   // scans are not actually performed as part of Shill, this value must be set
132   // by the Tether component.
133   void SetTetherScanState(bool is_scanning);
134 
135   // Asynchronously sets the list of prohibited technologies. The accepted
136   // values are the shill network technology identifiers. See also
137   // chromeos::onc::Validator::ValidateGlobalNetworkConfiguration().
138   void SetProhibitedTechnologies(
139       const std::vector<std::string>& prohibited_technologies);
140 
141   // Finds and returns a device state by |device_path| or NULL if not found.
142   const DeviceState* GetDeviceState(const std::string& device_path) const;
143 
144   // Finds and returns a device state by |type|. Returns NULL if not found.
145   const DeviceState* GetDeviceStateByType(const NetworkTypePattern& type) const;
146 
147   // Returns true if any device of |type| is scanning.
148   bool GetScanningByType(const NetworkTypePattern& type) const;
149 
150   // Finds and returns a network state by |service_path| or NULL if not found.
151   // Note: NetworkState is frequently updated asynchronously, i.e. properties
152   // are not always updated all at once. This will contain the most recent
153   // value for each property. To receive notifications when a property changes,
154   // observe this class and implement NetworkPropertyChanged().
155   const NetworkState* GetNetworkState(const std::string& service_path) const;
156 
157   // Returns the default network (which includes VPNs) based on the Shill
158   // Manager.DefaultNetwork property. Normally this is the same as
159   // ConnectedNetworkByType(NetworkTypePattern::Default()), but the timing might
160   // differ.
161   const NetworkState* DefaultNetwork() const;
162 
163   // Returns the primary connected network matching |type|, otherwise null.
164   const NetworkState* ConnectedNetworkByType(const NetworkTypePattern& type);
165 
166   // Returns the primary connecting network matching |type|, otherwise null.
167   const NetworkState* ConnectingNetworkByType(const NetworkTypePattern& type);
168 
169   // Returns the primary active network of matching |type|, otherwise null.
170   // See also GetActiveNetworkListByType.
171   const NetworkState* ActiveNetworkByType(const NetworkTypePattern& type);
172 
173   // Like ConnectedNetworkByType() but returns any matching visible network or
174   // NULL. Mostly useful for mobile networks where there is generally only one
175   // network. Note: O(N).
176   const NetworkState* FirstNetworkByType(const NetworkTypePattern& type);
177 
178   // Sets the |connect_requested_| property of a NetworkState for
179   // |service_path| if it exists. This is used to inform the UI that a network
180   // is connecting before the state is set in Shill. If |connect_requested| is
181   // true, NetworkState::IsConnectingState() will return true. This will cause
182   // the network to be sorted first and it will be part of the active list.
183   void SetNetworkConnectRequested(const std::string& service_path,
184                                   bool connect_requested);
185 
186   // Called from Chrome's network portal detector to indicate whether Chrome has
187   // detected that the network is in a captive portal state. This may or may
188   // not match the network's |is_captive_portal_| which is provided by Shill.
189   void SetNetworkChromePortalDetected(const std::string& service_path,
190                                       bool portal_detected);
191 
192   // Returns the aa:bb formatted hardware (MAC) address for the first connected
193   // network matching |type|, or an empty string if none is connected.
194   std::string FormattedHardwareAddressForType(const NetworkTypePattern& type);
195 
196   // Convenience method to call GetNetworkListByType(visible=true).
197   void GetVisibleNetworkListByType(const NetworkTypePattern& type,
198                                    NetworkStateList* list);
199 
200   // Convenience method for GetVisibleNetworkListByType(Default).
201   void GetVisibleNetworkList(NetworkStateList* list);
202 
203   // Sets |list| to contain the list of networks with matching |type| and the
204   // following properties:
205   // |configured_only| - if true only include networks where IsInProfile is true
206   // |visible_only| - if true only include networks in the visible Services list
207   // |limit| - if > 0 limits the number of results.
208   // The returned list contains a copy of NetworkState pointers which should not
209   // be stored or used beyond the scope of the calling function (i.e. they may
210   // later become invalid, but only on the UI thread). SortNetworkList() will be
211   // called if necessary to provide the states in a convenient order (see
212   // SortNetworkList for details).
213   void GetNetworkListByType(const NetworkTypePattern& type,
214                             bool configured_only,
215                             bool visible_only,
216                             size_t limit,
217                             NetworkStateList* list);
218 
219   // Sets |list| to contain the active networks matching |type|. An 'active'
220   // network is connecting or connected, and the first connected active network
221   // is the primary or 'default' network providing connectivity (which may be a
222   // VPN, use NetworkTypePattern::NonVirtual() to ignore VPNs). See
223   // GetNetworkListByType for notes on |list| results.
224   void GetActiveNetworkListByType(const NetworkTypePattern& type,
225                                   NetworkStateList* list);
226 
227   // Finds and returns the NetworkState associated with |service_path| or NULL
228   // if not found. If |configured_only| is true, only returns saved entries
229   // (IsInProfile is true).
230   const NetworkState* GetNetworkStateFromServicePath(
231       const std::string& service_path,
232       bool configured_only) const;
233 
234   // Finds and returns the NetworkState associated with |guid| or NULL if not
235   // found. This returns all entries (IsInProfile() may be true or false).
236   const NetworkState* GetNetworkStateFromGuid(const std::string& guid) const;
237 
238   // Creates a Tether NetworkState that has no underlying shill type or
239   // service. When initially created, it does not actually represent a real
240   // network. The |guid| provided must be non-empty. If a network with |guid|
241   // already exists, this method will do nothing. Use the provided |guid| to
242   // refer to and fetch this NetworkState in the future. Note that the
243   // |has_connected_to_host| parameter refers to whether the current device has
244   // already connected to the Tether host device providing this Tether network
245   // in the past.
246   void AddTetherNetworkState(const std::string& guid,
247                              const std::string& name,
248                              const std::string& carrier,
249                              int battery_percentage,
250                              int signal_strength,
251                              bool has_connected_to_host);
252 
253   // Updates the Tether properties (carrier, battery percentage, and signal
254   // strength) for a network which has already been added via
255   // AddTetherNetworkState. Returns whether the update was successful.
256   bool UpdateTetherNetworkProperties(const std::string& guid,
257                                      const std::string& carrier,
258                                      int battery_percentage,
259                                      int signal_strength);
260 
261   // Updates whether the Tether network with GUID |guid| has connected to the
262   // host device before, setting the value to true. Note that there is no way to
263   // change this value back to false. If no network with GUID |guid| is
264   // registered or if the network is registered and its HasConnectedToHost value
265   // was already true, this function does nothing. Returns whether the value was
266   // actually changed.
267   bool SetTetherNetworkHasConnectedToHost(const std::string& guid);
268 
269   // Remove a Tether NetworkState, using the same |guid| passed to
270   // AddTetherNetworkState(). If no network with GUID |guid| is registered, this
271   // function does nothing. Returns whether the network was actually removed.
272   bool RemoveTetherNetworkState(const std::string& guid);
273 
274   // Disassociates the Tether network specified by |tether_network_guid| from
275   // its associated Wi-Fi network. Returns whether the networkd were
276   // successfully disassociated.
277   bool DisassociateTetherNetworkStateFromWifiNetwork(
278       const std::string& tether_network_guid);
279 
280   // Inform NetworkStateHandler that the provided Tether network with the
281   // provided guid |tether_network_guid| is associated with the Wi-Fi network
282   // with the provided guid |wifi_network_guid|. This Wi-Fi network can now be
283   // hidden in the UI, and the Tether network will act as its proxy. Returns
284   // false if the association failed (e.g., one or both networks don't exist).
285   bool AssociateTetherNetworkStateWithWifiNetwork(
286       const std::string& tether_network_guid,
287       const std::string& wifi_network_guid);
288 
289   // Set the connection_state of the Tether NetworkState corresponding to the
290   // provided |guid| to "Disconnected". This will be reflected in the UI.
291   void SetTetherNetworkStateDisconnected(const std::string& guid);
292 
293   // Set the connection_state of the Tether NetworkState corresponding to the
294   // provided |guid| to "Connecting". This will be reflected in the UI.
295   void SetTetherNetworkStateConnecting(const std::string& guid);
296 
297   // Set the connection_state of the Tether NetworkState corresponding to the
298   // provided |guid| to "Connected". This will be reflected in the UI.
299   void SetTetherNetworkStateConnected(const std::string& guid);
300 
301   void set_tether_sort_delegate(
302       const TetherSortDelegate* tether_sort_delegate) {
303     tether_sort_delegate_ = tether_sort_delegate;
304   }
305 
306   // Sets |list| to contain the list of devices.  The returned list contains
307   // a copy of DeviceState pointers which should not be stored or used beyond
308   // the scope of the calling function (i.e. they may later become invalid, but
309   // only on the UI thread).
310   void GetDeviceList(DeviceStateList* list) const;
311 
312   // Like GetDeviceList() but only returns networks with matching |type|.
313   void GetDeviceListByType(const NetworkTypePattern& type,
314                            DeviceStateList* list) const;
315 
316   // Requests a network scan. This may trigger updates to the network
317   // list, which will trigger the appropriate observer calls.
318   // Note: If |type| is Cellular, a mobile network scan will be requested
319   // if supported. This is disruptive and should only be triggered by an
320   // explicit user action.
321   void RequestScan(const NetworkTypePattern& type);
322 
323   // Requests an update for an existing NetworkState, e.g. after configuring
324   // a network. This is a no-op if an update request is already pending. To
325   // ensure that a change is picked up, this must be called after Shill
326   // acknowledged it (e.g. in the callback of a SetProperties).
327   // When the properties are received, NetworkPropertiesUpdated will be
328   // signaled for each member of |observers_|, regardless of whether any
329   // properties actually changed. Note that this is a no-op for Tether networks.
330   void RequestUpdateForNetwork(const std::string& service_path);
331 
332   // Informs NetworkStateHandler to notify observers that the properties for
333   // the network may have changed. Called e.g. when the proxy properties may
334   // have changed.
335   void SendUpdateNotificationForNetwork(const std::string& service_path);
336 
337   // Clears the last_error value for the NetworkState for |service_path|.
338   void ClearLastErrorForNetwork(const std::string& service_path);
339 
340   // Sets the list of devices on which portal check is enabled.
341   void SetCheckPortalList(const std::string& check_portal_list);
342 
343   // Sets the Manager.WakeOnLan property. Note: we do not track this state, we
344   // only set it.
345   void SetWakeOnLanEnabled(bool enabled);
346 
347   // Sets the DHCP HostName property. Note: This does not directly set
348   // |hostname_|, it sets the Shill property and relies on Shill emitting the
349   // change which updates the cached |hostname_|. This ensures that Chrome and
350   // Shill are in sync.
351   void SetHostname(const std::string& hostname);
352 
353   // Returns the cached DHCP HostName property provided by Shill. Initialized
354   // to an empty string and set once the Manager properties are received.
355   const std::string& hostname() const { return hostname_; }
356 
357   // Enable or disable network bandwidth throttling, on all interfaces on the
358   // system. If |enabled| is true, |upload_rate_kbits| and |download_rate_kbits|
359   // are the desired rates (in kbits/s) to throttle to. If |enabled| is false,
360   // throttling is off, and the rates are ignored.
361   void SetNetworkThrottlingStatus(bool enabled,
362                                   uint32_t upload_rate_kbits,
363                                   uint32_t download_rate_kbits);
364 
365   // Sets the Fast Transition property. 802.11r Fast BSS Transition allows
366   // wireless Access Points to share information before a device initiates a
367   // reassociation. This allows devices to roam much more quickly.
368   void SetFastTransitionStatus(bool enabled);
369 
370   const std::string& GetCheckPortalListForTest() const {
371     return check_portal_list_;
372   }
373 
374   // Returns the NetworkState for the EthernetEAP service, which contains the
375   // EAP parameters used by the Ethernet network matching |service_path|, if it
376   // exists. If |connected_only| is true, only returns the EthernetEAP state
377   // if the Ethernet network is connected using EAP. Otherwise returns null.
378   const NetworkState* GetEAPForEthernet(const std::string& service_path,
379                                         bool connected_only);
380 
381   // Sets the |error_| property of the matching NetworkState for tests.
382   void SetErrorForTest(const std::string& service_path,
383                        const std::string& error);
384 
385   void SetDeviceStateUpdatedForTest(const std::string& device_path);
386 
387   // Sets |allow_only_policy_networks_to_connect_|,
388   // |allow_only_policy_networks_to_connect_if_available_| and
389   // |blocked_hex_ssids_| and calls |UpdateBlockedWifiNetworksInternal()|.
390   virtual void UpdateBlockedWifiNetworks(
391       bool only_managed,
392       bool available_only,
393       const std::vector<std::string>& blocked_hex_ssids);
394 
395   // Returns the NetworkState associated to the wifi device's
396   // available_managed_network_path or |nullptr| if no managed network is
397   // available.
398   const NetworkState* GetAvailableManagedWifiNetwork() const;
399 
400   // Returns true if the AllowOnlyPolicyNetworksToConnect policy is enabled or
401   // if the AllowOnlyPolicyNetworksToConnectIfAvailable policy is enabled and
402   // there is a managed wifi network available.
403   bool OnlyManagedWifiNetworksAllowed() const;
404 
405   bool default_network_is_metered() const {
406     return default_network_is_metered_;
407   }
408 
409   // Constructs and initializes an instance for testing.
410   static std::unique_ptr<NetworkStateHandler> InitializeForTest();
411 
412   // Default set of comma separated interfaces on which to enable
413   // portal checking.
414   static const char kDefaultCheckPortalList[];
415 
416  protected:
417   friend class NetworkHandler;
418   NetworkStateHandler();
419 
420   // ShillPropertyHandler::Listener overrides.
421 
422   // This adds new entries to |network_list_| or |device_list_| and deletes any
423   // entries that are no longer in the list.
424   void UpdateManagedList(ManagedState::ManagedType type,
425                          const base::ListValue& entries) override;
426 
427   // The list of profiles changed (i.e. a user has logged in). Re-request
428   // properties for all services since they may have changed.
429   void ProfileListChanged() override;
430 
431   // Parses the properties for the network service or device. Mostly calls
432   // managed->PropertyChanged(key, value) for each dictionary entry.
433   // |properties| is expected to be type DICTIONARY.
434   void UpdateManagedStateProperties(ManagedState::ManagedType type,
435                                     const std::string& path,
436                                     const base::Value& properties) override;
437 
438   // Called by ShillPropertyHandler when a watched service property changes.
439   void UpdateNetworkServiceProperty(const std::string& service_path,
440                                     const std::string& key,
441                                     const base::Value& value) override;
442 
443   // Called by ShillPropertyHandler when a watched device property changes.
444   void UpdateDeviceProperty(const std::string& device_path,
445                             const std::string& key,
446                             const base::Value& value) override;
447 
448   // Called by ShillPropertyHandler when a watched network or device
449   // IPConfig property changes. |properties| is expected to be type DICTIONARY.
450   void UpdateIPConfigProperties(ManagedState::ManagedType type,
451                                 const std::string& path,
452                                 const std::string& ip_config_path,
453                                 const base::Value& properties) override;
454 
455   void CheckPortalListChanged(const std::string& check_portal_list) override;
456   void HostnameChanged(const std::string& hostname) override;
457   void TechnologyListChanged() override;
458 
459   // Called by |shill_property_handler_| when the service or device list has
460   // changed and all entries have been updated. This updates the list and
461   // notifies observers.
462   void ManagedStateListChanged(ManagedState::ManagedType type) override;
463 
464   // Called when the default network service changes. Sets default_network_path_
465   // and notifies listeners.
466   void DefaultNetworkServiceChanged(const std::string& service_path) override;
467 
468   // Called after construction. Called explicitly by tests after adding
469   // test observers.
470   void InitShillPropertyHandler();
471 
472  private:
473   typedef std::map<std::string, std::string> SpecifierGuidMap;
474   friend class NetworkStateHandlerTest;
475   FRIEND_TEST_ALL_PREFIXES(NetworkStateHandlerTest, NetworkStateHandlerStub);
476   FRIEND_TEST_ALL_PREFIXES(NetworkStateHandlerTest, BlockedByPolicyBlocked);
477   FRIEND_TEST_ALL_PREFIXES(NetworkStateHandlerTest, BlockedByPolicyOnlyManaged);
478   FRIEND_TEST_ALL_PREFIXES(NetworkStateHandlerTest,
479                            BlockedByPolicyOnlyManagedIfAvailable);
480 
481   // Implementation for GetNetworkListByType and GetActiveNetworkListByType.
482   void GetNetworkListByTypeImpl(const NetworkTypePattern& type,
483                                 bool configured_only,
484                                 bool visible_only,
485                                 bool active_only,
486                                 size_t limit,
487                                 NetworkStateList* list);
488 
489   // Sorts the network list. Called when all network updates have been received,
490   // or when the network list is requested but the list is in an unsorted state.
491   // Networks are sorted as follows, maintaining the existing relative ordering:
492   // * Connected or connecting networks (should be listed first by Shill)
493   // * Visible non-wifi networks
494   // * Visible wifi networks
495   // * Hidden (wifi) networks
496   // If |ensure_cellular| is true, call EnsureCellularNetwork (which may
497   // remove a network from the list).
498   void SortNetworkList(bool ensure_cellular);
499 
500   // Updates UMA stats. Called once after all requested networks are updated.
501   void UpdateNetworkStats();
502 
503   // NetworkState specific method for UpdateManagedStateProperties which
504   // notifies observers. |properties| is expected to be type DICTIONARY.
505   void UpdateNetworkStateProperties(NetworkState* network,
506                                     const base::Value& properties);
507 
508   // Ensure a valid GUID for NetworkState.
509   void UpdateGuid(NetworkState* network);
510 
511   // Update networkState properties from the associated DeviceState.
512   void UpdateCellularStateFromDevice(NetworkState* network);
513 
514   // Cellular networks may not have an associated Shill Service (e.g. when the
515   // SIM is locked or a mobile network is not available). This returns a new
516   // default cellular network if necessary.
517   std::unique_ptr<NetworkState> MaybeCreateDefaultCellularNetwork();
518 
519   // Removes the default Cellular network if it exists. Called when there is
520   // more than one Cellular network in the list.
521   void RemoveDefaultCellularNetwork();
522 
523   // Sends NetworkListChanged() to observers and logs an event.
524   void NotifyNetworkListChanged();
525 
526   // Sends DeviceListChanged() to observers and logs an event.
527   void NotifyDeviceListChanged();
528 
529   // Non-const getters for managed entries. These are const so that they can
530   // be called by Get[Network|Device]State, even though they return non-const
531   // pointers.
532   DeviceState* GetModifiableDeviceState(const std::string& device_path) const;
533   DeviceState* GetModifiableDeviceStateByType(
534       const NetworkTypePattern& type) const;
535   NetworkState* GetModifiableNetworkState(
536       const std::string& service_path) const;
537   NetworkState* GetModifiableNetworkStateFromGuid(
538       const std::string& guid) const;
539   ManagedState* GetModifiableManagedState(const ManagedStateList* managed_list,
540                                           const std::string& path) const;
541 
542   // Gets the list specified by |type|.
543   ManagedStateList* GetManagedList(ManagedState::ManagedType type);
544 
545   // Helper function that calls NotifyNetworkConnectionStateChanged and,
546   // for the default network, OnDefaultNetworkConnectionStateChanged and
547   // NotifyDefaultNetworkChanged.
548   void OnNetworkConnectionStateChanged(NetworkState* network);
549 
550   // Verifies the connection state of the default network. Returns false
551   // if the connection state change should be ignored.
552   bool VerifyDefaultNetworkConnectionStateChange(NetworkState* network);
553 
554   // Notifies observers when a network's connection state changes.
555   void NotifyNetworkConnectionStateChanged(NetworkState* network);
556 
557   // Notifies observers when the default network or its properties change.
558   void NotifyDefaultNetworkChanged(const std::string& log_reason);
559 
560   // Notifies observers when the active state of any current or previously
561   // active network changes, or the active networks order changes.
562   bool ActiveNetworksChanged(const NetworkStateList& active_networks);
563   void NotifyIfActiveNetworksChanged();
564 
565   // Notifies observers about changes to |network|, including IPConfg.
566   void NotifyNetworkPropertiesUpdated(const NetworkState* network);
567 
568   // Notifies observers about changes to |device|, including IPConfigs.
569   void NotifyDevicePropertiesUpdated(const DeviceState* device);
570 
571   // Called to ask observers to scan for networks.
572   void NotifyScanRequested(const NetworkTypePattern& type);
573 
574   // Called whenever Device.Scanning state transitions to true.
575   void NotifyScanStarted(const DeviceState* device);
576 
577   // Called whenever Device.Scanning state transitions to false.
578   void NotifyScanCompleted(const DeviceState* device);
579 
580   // Helper function to log property updated events.
581   void LogPropertyUpdated(const ManagedState* network,
582                           const std::string& key,
583                           const base::Value& value);
584 
585   // Returns one technology type for |type|. This technology will be the
586   // highest priority technology in the type pattern.
587   std::string GetTechnologyForType(const NetworkTypePattern& type) const;
588 
589   // Returns all the technology types for |type|.
590   std::vector<std::string> GetTechnologiesForType(
591       const NetworkTypePattern& type) const;
592 
593   // Adds Tether networks to |list|, limiting the maximum size of |list| to be
594   // |limit|. If |get_active| is true, only active (i.e., connecting/connected)
595   // networks will be added; otherwise, only inactive networks will be added.
596   // The returned list contains a copy of NetworkState pointers which
597   // should not be stored or used beyond the scope of the calling
598   // function (i.e., they may later become invalid, but only on the UI thread).
599   // See AddTetherNetworkState() for more information about Tether networks.
600   void AppendTetherNetworksToList(bool get_active,
601                                   size_t limit,
602                                   NetworkStateList* list);
603 
604   // Set the connection_state of a Tether NetworkState corresponding to the
605   // provided |guid|.
606   void SetTetherNetworkStateConnectionState(
607       const std::string& guid,
608       const std::string& connection_state);
609 
610   // Ensures that the Tether DeviceState is present in |device_list_| if
611   // |tether_technology_state_| is not TECHNOLOGY_UNAVAILABLE and ensures that
612   // it is not present in |device_list_| if it is TECHNOLOGY_UNAVAILABLE.
613   void EnsureTetherDeviceState();
614 
615   // Updates the network's |blocked_by_policy_| depending on
616   // |allow_only_policy_networks_to_connect_| and |blocked_hex_ssids_|.
617   // Returns true if the value changed.
618   bool UpdateBlockedByPolicy(NetworkState* network) const;
619 
620   // Updates the device's |managed_network_available_| depending on the list of
621   // networks associated with this device. Calls
622   // |UpdateBlockedWifiNetworksInternal()| if the availability changed.
623   void UpdateManagedWifiNetworkAvailable();
624 
625   // Calls |UpdateBlockedByPolicy()| for each wifi network.
626   void UpdateBlockedWifiNetworksInternal();
627 
628   // Sets properties associated with the default network, currently the path and
629   // Metered.
630   void SetDefaultNetworkValues(const std::string& path, bool metered);
631 
632   // Shill property handler instance, owned by this class.
633   std::unique_ptr<internal::ShillPropertyHandler> shill_property_handler_;
634 
635   // Observer list
636   base::ObserverList<NetworkStateHandlerObserver, true>::Unchecked observers_;
637 
638   // List of managed network states
639   ManagedStateList network_list_;
640 
641   // List of managed Tether network states, which exist separately from
642   // |network_list_|.
643   ManagedStateList tether_network_list_;
644 
645   // List of active networks, used to limit ActiveNetworksChanged events.
646   class ActiveNetworkState;
647   std::vector<ActiveNetworkState> active_network_list_;
648 
649   // Set to true when the network list is sorted, cleared when network updates
650   // arrive. Used to trigger sorting when needed.
651   bool network_list_sorted_ = false;
652 
653   // List of managed device states
654   ManagedStateList device_list_;
655 
656   // Keeps track of the default network for notifying observers when it changes.
657   // Do not set this directly, use SetDefaultNetworkValues() instead.
658   std::string default_network_path_;
659 
660   // Tracks whether there is a connected default network and it is metered.
661   // Do not set this directly, use SetDefaultNetworkValues() instead.
662   bool default_network_is_metered_ = false;
663 
664   // List of interfaces on which portal check is enabled.
665   std::string check_portal_list_;
666 
667   // Tracks the default network portal state for triggering PortalStateChanged.
668   NetworkState::PortalState default_network_portal_state_ =
669       NetworkState::PortalState::kUnknown;
670 
671   // Tracks the default network proxy config for triggering PortalStateChanged.
672   base::Value default_network_proxy_config_;
673 
674   // DHCP Hostname.
675   std::string hostname_;
676 
677   // Map of network specifiers to guids. Contains an entry for each
678   // NetworkState that is not saved in a profile.
679   SpecifierGuidMap specifier_guid_map_;
680 
681   // The state corresponding to the Tether device type. This value is managed by
682   // the Tether component.
683   TechnologyState tether_technology_state_ =
684       TechnologyState::TECHNOLOGY_UNAVAILABLE;
685 
686   // Not owned by this instance.
687   const TetherSortDelegate* tether_sort_delegate_ = nullptr;
688 
689   // Ensure that Shutdown() gets called exactly once.
690   bool did_shutdown_ = false;
691 
692   // Ensure that we do not delete any networks while notifying observers.
693   bool notifying_network_observers_ = false;
694 
695   // Policies which control WiFi blocking (Controlled from
696   // |ManagedNetworkConfigurationHandler| by calling |UpdateBlockedNetworks()|).
697   bool allow_only_policy_networks_to_connect_ = false;
698   bool allow_only_policy_networks_to_connect_if_available_ = false;
699   std::vector<std::string> blocked_hex_ssids_;
700 
701   SEQUENCE_CHECKER(sequence_checker_);
702 
703   DISALLOW_COPY_AND_ASSIGN(NetworkStateHandler);
704 };
705 
706 }  // namespace chromeos
707 
708 #endif  // CHROMEOS_NETWORK_NETWORK_STATE_HANDLER_H_
709