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