network_state_handler.h revision 58537e28ecd584eab876aee8be7156509866d23a
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. flimflam::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& check_portal_list() const { return check_portal_list_; }
204
205  // Generates a DictionaryValue of all NetworkState properties. Currently
206  // provided for debugging purposes only.
207  void GetNetworkStatePropertiesForTest(
208      base::DictionaryValue* dictionary) const;
209
210  // Construct and initialize an instance for testing.
211  static NetworkStateHandler* InitializeForTest();
212
213  // Default set of comma separated interfaces on which to enable
214  // portal checking.
215  static const char kDefaultCheckPortalList[];
216
217 protected:
218  friend class NetworkHandler;
219  NetworkStateHandler();
220
221  // ShillPropertyHandler::Listener overrides.
222
223  // This adds new entries to the managed list specified by |type| and deletes
224  // any entries that are no longer in the list.
225  virtual void UpdateManagedList(ManagedState::ManagedType type,
226                                 const base::ListValue& entries) OVERRIDE;
227
228  // The list of profiles changed (i.e. a user has logged in). Re-request
229  // properties for all services since they may have changed.
230  virtual void ProfileListChanged() OVERRIDE;
231
232  // Parses the properties for the network service or device. Mostly calls
233  // managed->PropertyChanged(key, value) for each dictionary entry.
234  virtual void UpdateManagedStateProperties(
235      ManagedState::ManagedType type,
236      const std::string& path,
237      const base::DictionaryValue& properties) OVERRIDE;
238
239  // Called by ShillPropertyHandler when a watched service property changes.
240  virtual void UpdateNetworkServiceProperty(
241      const std::string& service_path,
242      const std::string& key,
243      const base::Value& value) OVERRIDE;
244
245  // Called by ShillPropertyHandler when a watched device property changes.
246  virtual void UpdateDeviceProperty(
247      const std::string& device_path,
248      const std::string& key,
249      const base::Value& value) OVERRIDE;
250
251  // Called by ShillPropertyHandler when the portal check list manager property
252  // changes.
253  virtual void CheckPortalListChanged(
254      const std::string& check_portal_list) OVERRIDE;
255
256  // Sends NetworkManagerChanged() to observers and logs an event.
257  virtual void NotifyManagerPropertyChanged() OVERRIDE;
258
259  // Called by |shill_property_handler_| when the service or device list has
260  // changed and all entries have been updated. This updates the list and
261  // notifies observers. If |type| == TYPE_NETWORK this also calls
262  // CheckDefaultNetworkChanged().
263  virtual void ManagedStateListChanged(
264      ManagedState::ManagedType type) OVERRIDE;
265
266  // Called after construction. Called explicitly by tests after adding
267  // test observers.
268  void InitShillPropertyHandler();
269
270 private:
271  typedef std::list<base::Closure> ScanCallbackList;
272  typedef std::map<std::string, ScanCallbackList> ScanCompleteCallbackMap;
273  friend class NetworkStateHandlerTest;
274  FRIEND_TEST_ALL_PREFIXES(NetworkStateHandlerTest, NetworkStateHandlerStub);
275
276  // NetworkState specific method for UpdateManagedStateProperties which
277  // notifies observers.
278  void UpdateNetworkStateProperties(NetworkState* network,
279                                    const base::DictionaryValue& properties);
280
281  // Non-const getters for managed entries. These are const so that they can
282  // be called by Get[Network|Device]State, even though they return non-const
283  // pointers.
284  DeviceState* GetModifiableDeviceState(const std::string& device_path) const;
285  NetworkState* GetModifiableNetworkState(
286      const std::string& service_path) const;
287  ManagedState* GetModifiableManagedState(const ManagedStateList* managed_list,
288                                          const std::string& path) const;
289
290  // Gets the list specified by |type|.
291  ManagedStateList* GetManagedList(ManagedState::ManagedType type);
292
293  // Helper function to notify observers. Calls CheckDefaultNetworkChanged().
294  void OnNetworkConnectionStateChanged(NetworkState* network);
295
296  // If the default network changed returns true and sets
297  // |default_network_path_|.
298  bool CheckDefaultNetworkChanged();
299
300  // Logs an event and notifies observers.
301  void OnDefaultNetworkChanged();
302
303  // Notifies observers and updates connecting_network_.
304  void NetworkPropertiesUpdated(const NetworkState* network);
305
306  // Called whenever Device.Scanning state transitions to false.
307  void ScanCompleted(const std::string& type);
308
309  // Returns the technology type for |type|.
310  std::string GetTechnologyForType(const NetworkTypePattern& type) const;
311
312  // Shill property handler instance, owned by this class.
313  scoped_ptr<internal::ShillPropertyHandler> shill_property_handler_;
314
315  // Observer list
316  ObserverList<NetworkStateHandlerObserver> observers_;
317
318  // List of managed network states
319  ManagedStateList network_list_;
320
321  // List of managed favorite states; this list includes all entries in
322  // Manager.ServiceCompleteList, but only entries with a non-empty Profile
323  // property are returned in GetFavoriteList().
324  ManagedStateList favorite_list_;
325
326  // List of managed device states
327  ManagedStateList device_list_;
328
329  // Keeps track of the default network for notifying observers when it changes.
330  std::string default_network_path_;
331
332  // List of interfaces on which portal check is enabled.
333  std::string check_portal_list_;
334
335  // Callbacks to run when a scan for the technology type completes.
336  ScanCompleteCallbackMap scan_complete_callbacks_;
337
338  DISALLOW_COPY_AND_ASSIGN(NetworkStateHandler);
339};
340
341}  // namespace chromeos
342
343#endif  // CHROMEOS_NETWORK_NETWORK_STATE_HANDLER_H_
344