Home | History | Annotate | Download | only in network
      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/network_type_pattern.h"
     23 #include "chromeos/network/shill_property_handler.h"
     24 
     25 namespace base {
     26 class DictionaryValue;
     27 class ListValue;
     28 class Value;
     29 }
     30 
     31 namespace tracked_objects {
     32 class Location;
     33 }
     34 
     35 namespace chromeos {
     36 
     37 class DeviceState;
     38 class NetworkState;
     39 class NetworkStateHandlerObserver;
     40 class NetworkStateHandlerTest;
     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 // Some notes about NetworkState and GUIDs:
     54 // * A NetworkState exists for all network services stored in a profile, and
     55 //   all "visible" networks (physically connected networks like ethernet and
     56 //   cellular or in-range wifi networks). If the network is stored in a profile,
     57 //   NetworkState.IsInProfile() will return true.
     58 // * "Visible" networks return true for NetworkState.visible().
     59 // * All networks saved to a profile will have a saved GUID that is persistent
     60 //   across sessions.
     61 // * Networks that are not saved to a profile will have a GUID assigned when
     62 //   the initial properties are received. The GUID will be consistent for
     63 //   the duration of a session, even if the network drops out and returns.
     64 
     65 class CHROMEOS_EXPORT NetworkStateHandler
     66     : public internal::ShillPropertyHandler::Listener {
     67  public:
     68   typedef std::vector<ManagedState*> ManagedStateList;
     69   typedef std::vector<const NetworkState*> NetworkStateList;
     70   typedef std::vector<const DeviceState*> DeviceStateList;
     71 
     72   enum TechnologyState {
     73     TECHNOLOGY_UNAVAILABLE,
     74     TECHNOLOGY_AVAILABLE,
     75     TECHNOLOGY_UNINITIALIZED,
     76     TECHNOLOGY_ENABLING,
     77     TECHNOLOGY_ENABLED
     78   };
     79 
     80   virtual ~NetworkStateHandler();
     81 
     82   // Add/remove observers.
     83   void AddObserver(NetworkStateHandlerObserver* observer,
     84                    const tracked_objects::Location& from_here);
     85   void RemoveObserver(NetworkStateHandlerObserver* observer,
     86                       const tracked_objects::Location& from_here);
     87 
     88   // Returns the state for technology |type|. Only
     89   // NetworkTypePattern::Primitive, ::Mobile and ::Ethernet are supported.
     90   TechnologyState GetTechnologyState(const NetworkTypePattern& type) const;
     91   bool IsTechnologyAvailable(const NetworkTypePattern& type) const {
     92     return GetTechnologyState(type) != TECHNOLOGY_UNAVAILABLE;
     93   }
     94   bool IsTechnologyEnabled(const NetworkTypePattern& type) const {
     95     return GetTechnologyState(type) == TECHNOLOGY_ENABLED;
     96   }
     97 
     98   // Asynchronously sets the technology enabled property for |type|. Only
     99   // NetworkTypePattern::Primitive, ::Mobile and ::Ethernet are supported.
    100   // Note: Modifies Manager state. Calls |error_callback| on failure.
    101   void SetTechnologyEnabled(
    102       const NetworkTypePattern& 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   const DeviceState* GetDeviceStateByType(const NetworkTypePattern& type) const;
    111 
    112   // Returns true if any device of |type| is scanning.
    113   bool GetScanningByType(const NetworkTypePattern& type) const;
    114 
    115   // Finds and returns a network state by |service_path| or NULL if not found.
    116   // Note: NetworkState is frequently updated asynchronously, i.e. properties
    117   // are not always updated all at once. This will contain the most recent
    118   // value for each property. To receive notifications when a property changes,
    119   // observe this class and implement NetworkPropertyChanged().
    120   const NetworkState* GetNetworkState(const std::string& service_path) const;
    121 
    122   // Returns the default network (which includes VPNs) based on the Shill
    123   // Manager.DefaultNetwork property. Normally this is the same as
    124   // ConnectedNetworkByType(NetworkTypePattern::Default()), but the timing might
    125   // differ.
    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 visible network or
    137   // NULL. Mostly useful for mobile networks where there is generally only one
    138   // network. Note: O(N).
    139   const NetworkState* FirstNetworkByType(const NetworkTypePattern& type);
    140 
    141   // Returns the aa:bb formatted hardware (MAC) address for the first connected
    142   // network matching |type|, or an empty string if none is connected.
    143   std::string FormattedHardwareAddressForType(
    144       const NetworkTypePattern& type) const;
    145 
    146   // Convenience method to call GetNetworkListByType(visible=true).
    147   void GetVisibleNetworkListByType(const NetworkTypePattern& type,
    148                                    NetworkStateList* list);
    149 
    150   // Convenience method for GetVisibleNetworkListByType(Default).
    151   void GetVisibleNetworkList(NetworkStateList* list);
    152 
    153   // Sets |list| to contain the list of networks with matching |type| and the
    154   // following properties:
    155   // |configured_only| - if true only include networks where IsInProfile is true
    156   // |visible_only| - if true only include networks in the visible Services list
    157   // |limit| - if > 0 limits the number of results.
    158   // The returned list contains a copy of NetworkState pointers which should not
    159   // be stored or used beyond the scope of the calling function (i.e. they may
    160   // later become invalid, but only on the UI thread). SortNetworkList() will be
    161   // called if necessary to provide the states in a convenient order (see
    162   // SortNetworkList for details).
    163   void GetNetworkListByType(const NetworkTypePattern& type,
    164                             bool configured_only,
    165                             bool visible_only,
    166                             int limit,
    167                             NetworkStateList* list);
    168 
    169   // Finds and returns the NetworkState associated with |service_path| or NULL
    170   // if not found. If |configured_only| is true, only returns saved entries
    171   // (IsInProfile is true).
    172   const NetworkState* GetNetworkStateFromServicePath(
    173       const std::string& service_path,
    174       bool configured_only) const;
    175 
    176   // Finds and returns the NetworkState associated with |guid| or NULL if not
    177   // found. This returns all entries (IsInProfile() may be true or false).
    178   const NetworkState* GetNetworkStateFromGuid(const std::string& guid) const;
    179 
    180   // Sets |list| to contain the list of devices.  The returned list contains
    181   // a copy of DeviceState pointers which should not be stored or used beyond
    182   // the scope of the calling function (i.e. they may later become invalid, but
    183   // only on the UI thread).
    184   void GetDeviceList(DeviceStateList* list) const;
    185 
    186   // Like GetDeviceList() but only returns networks with matching |type|.
    187   void GetDeviceListByType(const NetworkTypePattern& type,
    188                            DeviceStateList* list) const;
    189 
    190   // Requests a network scan. This may trigger updates to the network
    191   // list, which will trigger the appropriate observer calls.
    192   void RequestScan() const;
    193 
    194   // Request a scan if not scanning and run |callback| when the Scanning state
    195   // for any Device of network type |type| completes.
    196   void WaitForScan(const std::string& type, const base::Closure& callback);
    197 
    198   // Request a network scan then signal Shill to connect to the best available
    199   // networks when completed.
    200   void ConnectToBestWifiNetwork();
    201 
    202   // Request an update for an existing NetworkState, e.g. after configuring
    203   // a network. This is a no-op if an update request is already pending. To
    204   // ensure that a change is picked up, this must be called after Shill
    205   // acknowledged it (e.g. in the callback of a SetProperties).
    206   // When the properties are received, NetworkPropertiesUpdated will be
    207   // signaled for each member of |observers_|, regardless of whether any
    208   // properties actually changed.
    209   void RequestUpdateForNetwork(const std::string& service_path);
    210 
    211   // Clear the last_error value for the NetworkState for |service_path|.
    212   void ClearLastErrorForNetwork(const std::string& service_path);
    213 
    214   // Set the list of devices on which portal check is enabled.
    215   void SetCheckPortalList(const std::string& check_portal_list);
    216 
    217   const std::string& GetCheckPortalListForTest() const {
    218     return check_portal_list_;
    219   }
    220 
    221   // Returns the NetworkState of the EthernetEAP service, which contains the
    222   // EAP parameters used by the ethernet with |service_path|. If |service_path|
    223   // doesn't refer to an ethernet service or if the ethernet service is not
    224   // connected using EAP, returns NULL.
    225   const NetworkState* GetEAPForEthernet(const std::string& service_path);
    226 
    227   const std::string& default_network_path() const {
    228     return default_network_path_;
    229   }
    230 
    231   // Construct and initialize an instance for testing.
    232   static NetworkStateHandler* InitializeForTest();
    233 
    234   // Default set of comma separated interfaces on which to enable
    235   // portal checking.
    236   static const char kDefaultCheckPortalList[];
    237 
    238  protected:
    239   friend class NetworkHandler;
    240   NetworkStateHandler();
    241 
    242   // ShillPropertyHandler::Listener overrides.
    243 
    244   // This adds new entries to |network_list_| or |device_list_| and deletes any
    245   // entries that are no longer in the list.
    246   virtual void UpdateManagedList(ManagedState::ManagedType type,
    247                                  const base::ListValue& entries) OVERRIDE;
    248 
    249   // The list of profiles changed (i.e. a user has logged in). Re-request
    250   // properties for all services since they may have changed.
    251   virtual void ProfileListChanged() OVERRIDE;
    252 
    253   // Parses the properties for the network service or device. Mostly calls
    254   // managed->PropertyChanged(key, value) for each dictionary entry.
    255   virtual void UpdateManagedStateProperties(
    256       ManagedState::ManagedType type,
    257       const std::string& path,
    258       const base::DictionaryValue& properties) OVERRIDE;
    259 
    260   // Called by ShillPropertyHandler when a watched service property changes.
    261   virtual void UpdateNetworkServiceProperty(
    262       const std::string& service_path,
    263       const std::string& key,
    264       const base::Value& value) OVERRIDE;
    265 
    266   // Called by ShillPropertyHandler when a watched device property changes.
    267   virtual void UpdateDeviceProperty(
    268       const std::string& device_path,
    269       const std::string& key,
    270       const base::Value& value) OVERRIDE;
    271 
    272   // Called by ShillPropertyHandler when a watched network or device
    273   // IPConfig property changes.
    274   virtual void UpdateIPConfigProperties(
    275       ManagedState::ManagedType type,
    276       const std::string& path,
    277       const std::string& ip_config_path,
    278       const base::DictionaryValue& properties) OVERRIDE;
    279 
    280   // Called by ShillPropertyHandler when the portal check list manager property
    281   // changes.
    282   virtual void CheckPortalListChanged(
    283       const std::string& check_portal_list) OVERRIDE;
    284 
    285   // Called by ShillPropertyHandler when a technology list changes.
    286   virtual void TechnologyListChanged() OVERRIDE;
    287 
    288   // Called by |shill_property_handler_| when the service or device list has
    289   // changed and all entries have been updated. This updates the list and
    290   // notifies observers.
    291   virtual void ManagedStateListChanged(
    292       ManagedState::ManagedType type) OVERRIDE;
    293 
    294   // Called when the default network service changes. Sets default_network_path_
    295   // and notifies listeners.
    296   virtual void DefaultNetworkServiceChanged(
    297       const std::string& service_path) OVERRIDE;
    298 
    299   // Called after construction. Called explicitly by tests after adding
    300   // test observers.
    301   void InitShillPropertyHandler();
    302 
    303  private:
    304   typedef std::list<base::Closure> ScanCallbackList;
    305   typedef std::map<std::string, ScanCallbackList> ScanCompleteCallbackMap;
    306   typedef std::map<std::string, std::string> SpecifierGuidMap;
    307   friend class NetworkStateHandlerTest;
    308   FRIEND_TEST_ALL_PREFIXES(NetworkStateHandlerTest, NetworkStateHandlerStub);
    309 
    310   // Sorts the network list. Called when all network updates have been received,
    311   // or when the network list is requested but the list is in an unsorted state.
    312   // Networks are sorted as follows, maintaining the existing relative ordering:
    313   // * Connected or connecting networks (should be listed first by Shill)
    314   // * Visible non-wifi networks
    315   // * Visible wifi networks
    316   // * Hidden (wifi) networks
    317   void SortNetworkList();
    318 
    319   // Updates UMA stats. Called once after all requested networks are updated.
    320   void UpdateNetworkStats();
    321 
    322   // NetworkState specific method for UpdateManagedStateProperties which
    323   // notifies observers.
    324   void UpdateNetworkStateProperties(NetworkState* network,
    325                                     const base::DictionaryValue& properties);
    326 
    327   // Ensure a valid GUID for NetworkState.
    328   void UpdateGuid(NetworkState* network);
    329 
    330   // Sends DeviceListChanged() to observers and logs an event.
    331   void NotifyDeviceListChanged();
    332 
    333   // Non-const getters for managed entries. These are const so that they can
    334   // be called by Get[Network|Device]State, even though they return non-const
    335   // pointers.
    336   DeviceState* GetModifiableDeviceState(const std::string& device_path) const;
    337   NetworkState* GetModifiableNetworkState(
    338       const std::string& service_path) const;
    339   ManagedState* GetModifiableManagedState(const ManagedStateList* managed_list,
    340                                           const std::string& path) const;
    341 
    342   // Gets the list specified by |type|.
    343   ManagedStateList* GetManagedList(ManagedState::ManagedType type);
    344 
    345   // Helper function to notify observers. Calls CheckDefaultNetworkChanged().
    346   void OnNetworkConnectionStateChanged(NetworkState* network);
    347 
    348   // Notifies observers when the default network or its properties change.
    349   void NotifyDefaultNetworkChanged(const NetworkState* default_network);
    350 
    351   // Notifies observers about changes to |network|.
    352   void NotifyNetworkPropertiesUpdated(const NetworkState* network);
    353 
    354   // Called whenever Device.Scanning state transitions to false.
    355   void ScanCompleted(const std::string& type);
    356 
    357   // Returns one technology type for |type|. This technology will be the
    358   // highest priority technology in the type pattern.
    359   std::string GetTechnologyForType(const NetworkTypePattern& type) const;
    360 
    361   // Returns all the technology types for |type|.
    362   ScopedVector<std::string> GetTechnologiesForType(
    363       const NetworkTypePattern& type) const;
    364 
    365   // Shill property handler instance, owned by this class.
    366   scoped_ptr<internal::ShillPropertyHandler> shill_property_handler_;
    367 
    368   // Observer list
    369   ObserverList<NetworkStateHandlerObserver> observers_;
    370 
    371   // List of managed network states
    372   ManagedStateList network_list_;
    373 
    374   // Set to true when the network list is sorted, cleared when network updates
    375   // arrive. Used to trigger sorting when needed.
    376   bool network_list_sorted_;
    377 
    378   // List of managed device states
    379   ManagedStateList device_list_;
    380 
    381   // Keeps track of the default network for notifying observers when it changes.
    382   std::string default_network_path_;
    383 
    384   // List of interfaces on which portal check is enabled.
    385   std::string check_portal_list_;
    386 
    387   // Callbacks to run when a scan for the technology type completes.
    388   ScanCompleteCallbackMap scan_complete_callbacks_;
    389 
    390   // Map of network specifiers to guids. Contains an entry for each
    391   // NetworkState that is not saved in a profile.
    392   SpecifierGuidMap specifier_guid_map_;
    393 
    394   DISALLOW_COPY_AND_ASSIGN(NetworkStateHandler);
    395 };
    396 
    397 }  // namespace chromeos
    398 
    399 #endif  // CHROMEOS_NETWORK_NETWORK_STATE_HANDLER_H_
    400