network_state_handler.h revision 4e180b6a0b4720a9b8e9e959a882386f690f08ff
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 FavoriteState associated to DefaultNetwork. Returns NULL if,
129  // and only if, DefaultNetwork returns NULL.
130  const FavoriteState* DefaultFavoriteNetwork() const;
131
132  // Returns the primary connected network of matching |type|, otherwise NULL.
133  const NetworkState* ConnectedNetworkByType(
134      const NetworkTypePattern& type) const;
135
136  // Like ConnectedNetworkByType() but returns a connecting network or NULL.
137  const NetworkState* ConnectingNetworkByType(
138      const NetworkTypePattern& type) const;
139
140  // Like ConnectedNetworkByType() but returns any matching network or NULL.
141  // Mostly useful for mobile networks where there is generally only one
142  // network. Note: O(N).
143  const NetworkState* FirstNetworkByType(const NetworkTypePattern& type) const;
144
145  // Returns the hardware (MAC) address for the first connected network
146  // matching |type|, or an empty string if none is connected.
147  std::string HardwareAddressForType(const NetworkTypePattern& type) const;
148  // Same as above but in aa:bb format.
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  // Sets |list| to contain the list of favorite (aka "preferred") networks.
169  // See GetNetworkList() for usage, and notes for |favorite_list_|.
170  // Favorites that are visible have the same path() as the entries in
171  // GetNetworkList(), so GetNetworkState() can be used to determine if a
172  // favorite is visible and retrieve the complete properties (and vice-versa).
173  void GetFavoriteList(FavoriteStateList* list) const;
174
175  // Like GetFavoriteList() but only returns favorites with matching |type|.
176  void GetFavoriteListByType(const NetworkTypePattern& type,
177                             FavoriteStateList* list) const;
178
179  // Finds and returns a favorite state by |service_path| or NULL if not found.
180  const FavoriteState* GetFavoriteState(const std::string& service_path) const;
181
182  // Requests a network scan. This may trigger updates to the network
183  // list, which will trigger the appropriate observer calls.
184  void RequestScan() const;
185
186  // Request a scan if not scanning and run |callback| when the Scanning state
187  // for any Device of network type |type| completes.
188  void WaitForScan(const std::string& type, const base::Closure& callback);
189
190  // Request a network scan then signal Shill to connect to the best available
191  // networks when completed.
192  void ConnectToBestWifiNetwork();
193
194  // Request an update for an existing NetworkState, e.g. after configuring
195  // a network. This is a no-op if an update request is already pending. To
196  // ensure that a change is picked up, this must be called after Shill
197  // acknowledged it (e.g. in the callback of a SetProperties).
198  // When the properties are received, NetworkPropertiesUpdated will be
199  // signaled for each member of |observers_|, regardless of whether any
200  // properties actually changed.
201  void RequestUpdateForNetwork(const std::string& service_path);
202
203  // Request an update for all existing NetworkState entries, e.g. after
204  // loading an ONC configuration file that may have updated one or more
205  // existing networks.
206  void RequestUpdateForAllNetworks();
207
208  // Set the list of devices on which portal check is enabled.
209  void SetCheckPortalList(const std::string& check_portal_list);
210
211  const std::string& GetCheckPortalListForTest() const {
212    return check_portal_list_;
213  }
214
215  // Returns the FavoriteState of the EthernetEAP service, which contains the
216  // EAP parameters used by the ethernet with |service_path|. If |service_path|
217  // doesn't refer to an ethernet service or if the ethernet service is not
218  // connected using EAP, returns NULL.
219  const FavoriteState* GetEAPForEthernet(const std::string& service_path) const;
220
221  // Generates a DictionaryValue of all NetworkState properties. Currently
222  // provided for debugging purposes only.
223  void GetNetworkStatePropertiesForTest(
224      base::DictionaryValue* dictionary) const;
225
226  // Construct and initialize an instance for testing.
227  static NetworkStateHandler* InitializeForTest();
228
229  // Default set of comma separated interfaces on which to enable
230  // portal checking.
231  static const char kDefaultCheckPortalList[];
232
233 protected:
234  friend class NetworkHandler;
235  NetworkStateHandler();
236
237  // ShillPropertyHandler::Listener overrides.
238
239  // This adds new entries to the managed list specified by |type| and deletes
240  // any entries that are no longer in the list.
241  virtual void UpdateManagedList(ManagedState::ManagedType type,
242                                 const base::ListValue& entries) OVERRIDE;
243
244  // The list of profiles changed (i.e. a user has logged in). Re-request
245  // properties for all services since they may have changed.
246  virtual void ProfileListChanged() OVERRIDE;
247
248  // Parses the properties for the network service or device. Mostly calls
249  // managed->PropertyChanged(key, value) for each dictionary entry.
250  virtual void UpdateManagedStateProperties(
251      ManagedState::ManagedType type,
252      const std::string& path,
253      const base::DictionaryValue& properties) OVERRIDE;
254
255  // Called by ShillPropertyHandler when a watched service property changes.
256  virtual void UpdateNetworkServiceProperty(
257      const std::string& service_path,
258      const std::string& key,
259      const base::Value& value) OVERRIDE;
260
261  // Called by ShillPropertyHandler when a watched device property changes.
262  virtual void UpdateDeviceProperty(
263      const std::string& device_path,
264      const std::string& key,
265      const base::Value& value) OVERRIDE;
266
267  // Called by ShillPropertyHandler when the portal check list manager property
268  // changes.
269  virtual void CheckPortalListChanged(
270      const std::string& check_portal_list) OVERRIDE;
271
272  // Called by ShillPropertyHandler when a technology list changes.
273  virtual void TechnologyListChanged() OVERRIDE;
274
275  // Called by |shill_property_handler_| when the service or device list has
276  // changed and all entries have been updated. This updates the list and
277  // notifies observers. If |type| == TYPE_NETWORK this also calls
278  // CheckDefaultNetworkChanged().
279  virtual void ManagedStateListChanged(
280      ManagedState::ManagedType type) OVERRIDE;
281
282  // Called after construction. Called explicitly by tests after adding
283  // test observers.
284  void InitShillPropertyHandler();
285
286 private:
287  typedef std::list<base::Closure> ScanCallbackList;
288  typedef std::map<std::string, ScanCallbackList> ScanCompleteCallbackMap;
289  friend class NetworkStateHandlerTest;
290  FRIEND_TEST_ALL_PREFIXES(NetworkStateHandlerTest, NetworkStateHandlerStub);
291
292  // NetworkState specific method for UpdateManagedStateProperties which
293  // notifies observers.
294  void UpdateNetworkStateProperties(NetworkState* network,
295                                    const base::DictionaryValue& properties);
296
297  // Sends DeviceListChanged() to observers and logs an event.
298  void NotifyDeviceListChanged();
299
300  // Non-const getters for managed entries. These are const so that they can
301  // be called by Get[Network|Device]State, even though they return non-const
302  // pointers.
303  DeviceState* GetModifiableDeviceState(const std::string& device_path) const;
304  NetworkState* GetModifiableNetworkState(
305      const std::string& service_path) const;
306  ManagedState* GetModifiableManagedState(const ManagedStateList* managed_list,
307                                          const std::string& path) const;
308
309  // Gets the list specified by |type|.
310  ManagedStateList* GetManagedList(ManagedState::ManagedType type);
311
312  // Helper function to notify observers. Calls CheckDefaultNetworkChanged().
313  void OnNetworkConnectionStateChanged(NetworkState* network);
314
315  // If the default network changed returns true and sets
316  // |default_network_path_|.
317  bool CheckDefaultNetworkChanged();
318
319  // Logs an event and notifies observers.
320  void OnDefaultNetworkChanged();
321
322  // Notifies observers about changes to |network|.
323  void NetworkPropertiesUpdated(const NetworkState* network);
324
325  // Called whenever Device.Scanning state transitions to false.
326  void ScanCompleted(const std::string& type);
327
328  // Returns the technology type for |type|.
329  std::string GetTechnologyForType(const NetworkTypePattern& type) const;
330
331  // Shill property handler instance, owned by this class.
332  scoped_ptr<internal::ShillPropertyHandler> shill_property_handler_;
333
334  // Observer list
335  ObserverList<NetworkStateHandlerObserver> observers_;
336
337  // List of managed network states
338  ManagedStateList network_list_;
339
340  // List of managed favorite states; this list includes all entries in
341  // Manager.ServiceCompleteList, but only entries with a non-empty Profile
342  // property are returned in GetFavoriteList().
343  ManagedStateList favorite_list_;
344
345  // List of managed device states
346  ManagedStateList device_list_;
347
348  // Keeps track of the default network for notifying observers when it changes.
349  std::string default_network_path_;
350
351  // List of interfaces on which portal check is enabled.
352  std::string check_portal_list_;
353
354  // Callbacks to run when a scan for the technology type completes.
355  ScanCompleteCallbackMap scan_complete_callbacks_;
356
357  DISALLOW_COPY_AND_ASSIGN(NetworkStateHandler);
358};
359
360}  // namespace chromeos
361
362#endif  // CHROMEOS_NETWORK_NETWORK_STATE_HANDLER_H_
363