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