network_state_handler.h revision 424c4d7b64af9d0d8fd9624f381f469654d5e3d2
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 <set>
10#include <string>
11#include <vector>
12
13#include "base/callback_forward.h"
14#include "base/gtest_prod_util.h"
15#include "base/memory/scoped_ptr.h"
16#include "base/observer_list.h"
17#include "chromeos/chromeos_export.h"
18#include "chromeos/network/managed_state.h"
19#include "chromeos/network/network_handler.h"
20#include "chromeos/network/network_handler_callbacks.h"
21#include "chromeos/network/shill_property_handler.h"
22
23namespace base {
24class DictionaryValue;
25class ListValue;
26class Value;
27}
28
29namespace tracked_objects {
30class Location;
31}
32
33namespace chromeos {
34
35class DeviceState;
36class NetworkState;
37class NetworkStateHandlerObserver;
38class NetworkStateHandlerTest;
39
40// Class for tracking the list of visible networks and their properties.
41//
42// This class maps essential properties from the connection manager (Shill) for
43// each visible network. It is not used to change the properties of services or
44// devices, only global (manager) properties.
45//
46// All getters return the currently cached properties. This class is expected to
47// keep properties up to date by managing the appropriate Shill observers.
48// It will invoke its own more specific observer methods when the specified
49// changes occur.
50//
51// Most *ByType or *ForType methods will accept any of the following  for
52// |type|. See individual methods for specific notes.
53// * Any type defined in service_constants.h (e.g. flimflam::kTypeWifi)
54// * kMatchTypeDefault returns the default (active) network
55// * kMatchTypeNonVirtual returns the primary non virtual network
56// * kMatchTypeWireless returns the primary wireless network
57// * kMatchTypeMobile returns the primary cellular or wimax network
58
59class CHROMEOS_EXPORT NetworkStateHandler
60    : public internal::ShillPropertyHandler::Listener {
61 public:
62  typedef std::vector<ManagedState*> ManagedStateList;
63  typedef std::vector<const NetworkState*> NetworkStateList;
64  typedef std::vector<const DeviceState*> DeviceStateList;
65  typedef std::vector<const FavoriteState*> FavoriteStateList;
66
67  enum TechnologyState {
68    TECHNOLOGY_UNAVAILABLE,
69    TECHNOLOGY_AVAILABLE,
70    TECHNOLOGY_UNINITIALIZED,
71    TECHNOLOGY_ENABLING,
72    TECHNOLOGY_ENABLED
73  };
74
75  virtual ~NetworkStateHandler();
76
77  // Add/remove observers.
78  void AddObserver(NetworkStateHandlerObserver* observer,
79                   const tracked_objects::Location& from_here);
80  void RemoveObserver(NetworkStateHandlerObserver* observer,
81                      const tracked_objects::Location& from_here);
82
83  // Requests all Manager properties, specifically to update the complete
84  // list of services which determines the list of Favorites. This should be
85  // called any time a new service is configured or a Profile is loaded.
86  void UpdateManagerProperties();
87
88  // Returns the state for technology |type|. kMatchTypeMobile (only) is
89  // also supported.
90  TechnologyState GetTechnologyState(const std::string& type) const;
91  bool IsTechnologyAvailable(const std::string& type) const {
92    return GetTechnologyState(type) != TECHNOLOGY_UNAVAILABLE;
93  }
94  bool IsTechnologyEnabled(const std::string& type) const {
95    return GetTechnologyState(type) == TECHNOLOGY_ENABLED;
96  }
97
98  // Asynchronously sets the technology enabled property for |type|.
99  // kMatchTypeMobile (only) is also supported.
100  // Note: Modifies Manager state. Calls |error_callback| on failure.
101  void SetTechnologyEnabled(
102      const std::string& type,
103      bool enabled,
104      const network_handler::ErrorCallback& error_callback);
105
106  // Finds and returns a device state by |device_path| or NULL if not found.
107  const DeviceState* GetDeviceState(const std::string& device_path) const;
108
109  // Finds and returns a device state by |type|. Returns NULL if not found.
110  // See note above for valid types.
111  const DeviceState* GetDeviceStateByType(const std::string& type) const;
112
113  // Returns true if any device of |type| is scanning.
114  // See note above for valid types.
115  bool GetScanningByType(const std::string& type) const;
116
117  // Finds and returns a network state by |service_path| or NULL if not found.
118  // Note: NetworkState is frequently updated asynchronously, i.e. properties
119  // are not always updated all at once. This will contain the most recent
120  // value for each property. To receive notifications when a property changes,
121  // observe this class and implement NetworkPropertyChanged().
122  const NetworkState* GetNetworkState(const std::string& service_path) const;
123
124  // Returns the default connected network (which includes VPNs) or NULL.
125  // This is equivalent to ConnectedNetworkByType(kMatchTypeDefault).
126  const NetworkState* DefaultNetwork() const;
127
128  // Returns the primary connected network of matching |type|, otherwise NULL.
129  // See note above for valid types.
130  const NetworkState* ConnectedNetworkByType(const std::string& type) const;
131
132  // Like ConnectedNetworkByType() but returns a connecting network or NULL.
133  const NetworkState* ConnectingNetworkByType(const std::string& type) const;
134
135  // Like ConnectedNetworkByType() but returns any matching network or NULL.
136  // Mostly useful for mobile networks where there is generally only one
137  // network. Note: O(N).
138  const NetworkState* FirstNetworkByType(const std::string& type) const;
139
140  // Returns the hardware (MAC) address for the first connected network
141  // matching |type|, or an empty string if none.
142  // See note above for valid types.
143  std::string HardwareAddressForType(const std::string& type) const;
144  // Same as above but in aa:bb format.
145  std::string FormattedHardwareAddressForType(const std::string& type) const;
146
147  // Sets |list| to contain the list of networks.  The returned list contains
148  // a copy of NetworkState pointers which should not be stored or used beyond
149  // the scope of the calling function (i.e. they may later become invalid, but
150  // only on the UI thread).
151  void GetNetworkList(NetworkStateList* list) const;
152
153  // Like GetNetworkList() but only returns networks with matching |type|.
154  void GetNetworkListByType(const std::string& type,
155                            NetworkStateList* list) const;
156
157  // Sets |list| to contain the list of devices.  The returned list contains
158  // a copy of DeviceState pointers which should not be stored or used beyond
159  // the scope of the calling function (i.e. they may later become invalid, but
160  // only on the UI thread).
161  void GetDeviceList(DeviceStateList* list) const;
162
163  // Sets |list| to contain the list of favorite (aka "preferred") networks.
164  // See GetNetworkList() for usage, and notes for |favorite_list_|.
165  // Favorites that are visible have the same path() as the entries in
166  // GetNetworkList(), so GetNetworkState() can be used to determine if a
167  // favorite is visible and retrieve the complete properties (and vice-versa).
168  void GetFavoriteList(FavoriteStateList* list) const;
169
170  // Finds and returns a favorite state by |service_path| or NULL if not found.
171  const FavoriteState* GetFavoriteState(const std::string& service_path) const;
172
173  // Requests a network scan. This may trigger updates to the network
174  // list, which will trigger the appropriate observer calls.
175  void RequestScan() const;
176
177  // Request a scan if not scanning and run |callback| when the Scanning state
178  // for any Device matching |type| completes.
179  void WaitForScan(const std::string& type, const base::Closure& callback);
180
181  // Request a network scan then signal Shill to connect to the best available
182  // networks when completed.
183  void ConnectToBestWifiNetwork();
184
185  // Request an update for an existing NetworkState, e.g. after configuring
186  // a network. This is a no-op if an update request is already pending. To
187  // ensure that a change is picked up, this must be called after Shill
188  // acknowledged it (e.g. in the callback of a SetProperties).
189  // When the properties are received, NetworkPropertiesUpdated will be
190  // signaled for each member of |observers_|, regardless of whether any
191  // properties actually changed.
192  void RequestUpdateForNetwork(const std::string& service_path);
193
194  // Request an update for all existing NetworkState entries, e.g. after
195  // loading an ONC configuration file that may have updated one or more
196  // existing networks.
197  void RequestUpdateForAllNetworks();
198
199  // Set the list of devices on which portal check is enabled.
200  void SetCheckPortalList(const std::string& check_portal_list);
201
202  const std::string& check_portal_list() const { return check_portal_list_; }
203
204  // Generates a DictionaryValue of all NetworkState properties. Currently
205  // provided for debugging purposes only.
206  void GetNetworkStatePropertiesForTest(
207      base::DictionaryValue* dictionary) const;
208
209  // Construct and initialize an instance for testing.
210  static NetworkStateHandler* InitializeForTest();
211
212  static const char kMatchTypeDefault[];
213  static const char kMatchTypeWireless[];
214  static const char kMatchTypeMobile[];
215  static const char kMatchTypeNonVirtual[];
216
217  // Default set of comma separated interfaces on which to enable
218  // portal checking.
219  static const char kDefaultCheckPortalList[];
220
221 protected:
222  friend class NetworkHandler;
223  NetworkStateHandler();
224
225  // ShillPropertyHandler::Listener overrides.
226
227  // This adds new entries to the managed list specified by |type| and deletes
228  // any entries that are no longer in the list.
229  virtual void UpdateManagedList(ManagedState::ManagedType type,
230                                 const base::ListValue& entries) OVERRIDE;
231
232  // The list of profiles changed (i.e. a user has logged in). Re-request
233  // properties for all services since they may have changed.
234  virtual void ProfileListChanged() OVERRIDE;
235
236  // Parses the properties for the network service or device. Mostly calls
237  // managed->PropertyChanged(key, value) for each dictionary entry.
238  virtual void UpdateManagedStateProperties(
239      ManagedState::ManagedType type,
240      const std::string& path,
241      const base::DictionaryValue& properties) OVERRIDE;
242
243  // Called by ShillPropertyHandler when a watched service property changes.
244  virtual void UpdateNetworkServiceProperty(
245      const std::string& service_path,
246      const std::string& key,
247      const base::Value& value) OVERRIDE;
248
249  // Called by ShillPropertyHandler when a watched device property changes.
250  virtual void UpdateDeviceProperty(
251      const std::string& device_path,
252      const std::string& key,
253      const base::Value& value) OVERRIDE;
254
255  // Called by ShillPropertyHandler when the portal check list manager property
256  // changes.
257  virtual void CheckPortalListChanged(
258      const std::string& check_portal_list) OVERRIDE;
259
260  // Sends NetworkManagerChanged() to observers and logs an event.
261  virtual void NotifyManagerPropertyChanged() OVERRIDE;
262
263  // Called by |shill_property_handler_| when the service or device list has
264  // changed and all entries have been updated. This updates the list and
265  // notifies observers. If |type| == TYPE_NETWORK this also calls
266  // CheckDefaultNetworkChanged().
267  virtual void ManagedStateListChanged(
268      ManagedState::ManagedType type) OVERRIDE;
269
270  // Called after construction. Called explicitly by tests after adding
271  // test observers.
272  void InitShillPropertyHandler();
273
274 private:
275  typedef std::list<base::Closure> ScanCallbackList;
276  typedef std::map<std::string, ScanCallbackList> ScanCompleteCallbackMap;
277  friend class NetworkStateHandlerTest;
278  FRIEND_TEST_ALL_PREFIXES(NetworkStateHandlerTest, NetworkStateHandlerStub);
279
280  // NetworkState specific method for UpdateManagedStateProperties which
281  // notifies observers.
282  void UpdateNetworkStateProperties(NetworkState* network,
283                                    const base::DictionaryValue& properties);
284
285  // Non-const getters for managed entries. These are const so that they can
286  // be called by Get[Network|Device]State, even though they return non-const
287  // pointers.
288  DeviceState* GetModifiableDeviceState(const std::string& device_path) const;
289  NetworkState* GetModifiableNetworkState(
290      const std::string& service_path) const;
291  ManagedState* GetModifiableManagedState(const ManagedStateList* managed_list,
292                                          const std::string& path) const;
293
294  // Gets the list specified by |type|.
295  ManagedStateList* GetManagedList(ManagedState::ManagedType type);
296
297  // Helper function to notify observers. Calls CheckDefaultNetworkChanged().
298  void OnNetworkConnectionStateChanged(NetworkState* network);
299
300  // If the default network changed returns true and sets
301  // |default_network_path_|.
302  bool CheckDefaultNetworkChanged();
303
304  // Logs an event and notifies observers.
305  void OnDefaultNetworkChanged();
306
307  // Notifies observers and updates connecting_network_.
308  void NetworkPropertiesUpdated(const NetworkState* network);
309
310  // Called whenever Device.Scanning state transitions to false.
311  void ScanCompleted(const std::string& type);
312
313  // Returns the technology type for |type|.
314  std::string GetTechnologyForType(const std::string& type) const;
315
316  // Shill property handler instance, owned by this class.
317  scoped_ptr<internal::ShillPropertyHandler> shill_property_handler_;
318
319  // Observer list
320  ObserverList<NetworkStateHandlerObserver> observers_;
321
322  // List of managed network states
323  ManagedStateList network_list_;
324
325  // List of managed favorite states; this list includes all entries in
326  // Manager.ServiceCompleteList, but only entries with a non-empty Profile
327  // property are returned in GetFavoriteList().
328  ManagedStateList favorite_list_;
329
330  // List of managed device states
331  ManagedStateList device_list_;
332
333  // Keeps track of the default network for notifying observers when it changes.
334  std::string default_network_path_;
335
336  // List of interfaces on which portal check is enabled.
337  std::string check_portal_list_;
338
339  // Callbacks to run when a scan for the technology type completes.
340  ScanCompleteCallbackMap scan_complete_callbacks_;
341
342  DISALLOW_COPY_AND_ASSIGN(NetworkStateHandler);
343};
344
345}  // namespace chromeos
346
347#endif  // CHROMEOS_NETWORK_NETWORK_STATE_HANDLER_H_
348