1 //
2 // Copyright (C) 2012 The Android Open Source Project
3 //
4 // Licensed under the Apache License, Version 2.0 (the "License");
5 // you may not use this file except in compliance with the License.
6 // You may obtain a copy of the License at
7 //
8 //      http://www.apache.org/licenses/LICENSE-2.0
9 //
10 // Unless required by applicable law or agreed to in writing, software
11 // distributed under the License is distributed on an "AS IS" BASIS,
12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 // See the License for the specific language governing permissions and
14 // limitations under the License.
15 //
16 
17 #ifndef SHILL_MANAGER_H_
18 #define SHILL_MANAGER_H_
19 
20 #include <map>
21 #include <memory>
22 #include <string>
23 #include <vector>
24 
25 #include <base/cancelable_callback.h>
26 #include <base/files/file_path.h>
27 #include <base/macros.h>
28 #include <base/memory/ref_counted.h>
29 #include <base/memory/weak_ptr.h>
30 #if defined(__ANDROID__)
31 #include <dbus/service_constants.h>
32 #else
33 #include <chromeos/dbus/service_constants.h>
34 #endif  // __ANDROID__
35 #include <gtest/gtest_prod.h>  // for FRIEND_TEST
36 
37 #include "shill/cellular/modem_info.h"
38 #include "shill/crypto_util_proxy.h"
39 #include "shill/dhcp_properties.h"
40 #include "shill/device.h"
41 #include "shill/device_info.h"
42 #include "shill/event_dispatcher.h"
43 #include "shill/geolocation_info.h"
44 #include "shill/hook_table.h"
45 #include "shill/metrics.h"
46 #include "shill/net/ip_address.h"
47 #include "shill/power_manager.h"
48 #include "shill/profile.h"
49 #include "shill/property_store.h"
50 #include "shill/service.h"
51 #include "shill/upstart/upstart.h"
52 #include "shill/wimax/wimax_provider.h"
53 
54 namespace shill {
55 
56 class ControlInterface;
57 class DeviceClaimer;
58 class DefaultProfile;
59 class Error;
60 class EventDispatcher;
61 class IPAddressStore;
62 class ManagerAdaptorInterface;
63 class Resolver;
64 class StoreInterface;
65 class VPNProvider;
66 
67 #if !defined(DISABLE_WIFI)
68 class WiFiProvider;
69 #if defined(__BRILLO__)
70 class RPCServiceWatcherInterface;
71 class WiFiDriverHal;
72 #endif  // __BRILLO__
73 #endif  // DISABLE_WIFI
74 
75 #if !defined(DISABLE_WIRED_8021X)
76 class EthernetEapProvider;
77 #endif  // DISABLE_WIRED_8021X
78 
79 class Manager : public base::SupportsWeakPtr<Manager> {
80  public:
81   typedef base::Callback<void(const ServiceRefPtr& service)> ServiceCallback;
82 
83   struct Properties {
84    public:
PropertiesProperties85     Properties()
86         : offline_mode(false),
87           portal_check_interval_seconds(0),
88           arp_gateway(true),
89           connection_id_salt(0),
90           minimum_mtu(IPConfig::kUndefinedMTU) {}
91     bool offline_mode;
92     std::string check_portal_list;
93     std::string country;
94     int32_t portal_check_interval_seconds;
95     std::string portal_url;
96     std::string host_name;
97     // Whether to ARP for the default gateway in the DHCP client after
98     // acquiring a lease.
99     bool arp_gateway;
100     // Comma-separated list of technologies for which link-monitoring is
101     // enabled.
102     std::string link_monitor_technologies;
103     // Comma-separated list of technologies for which auto-connect is disabled.
104     std::string no_auto_connect_technologies;
105     // Comma-separated list of technologies that should never be enabled.
106     std::string prohibited_technologies;
107     // Comma-separated list of DNS search paths to be ignored.
108     std::string ignored_dns_search_paths;
109     // Comma-separated list of DNS servers to prepend to resolver list.
110     std::string prepend_dns_servers;
111     // Salt value use for calculating network connection ID.
112     int connection_id_salt;
113     // The minimum MTU value that will be respected in DHCP responses.
114     int minimum_mtu;
115   };
116 
117   Manager(ControlInterface* control_interface,
118           EventDispatcher* dispatcher,
119           Metrics* metrics,
120           const std::string& run_directory,
121           const std::string& storage_directory,
122           const std::string& user_storage_directory);
123   virtual ~Manager();
124 
125   void RegisterAsync(const base::Callback<void(bool)>& completion_callback);
126 
127   virtual void SetBlacklistedDevices(
128       const std::vector<std::string>& blacklisted_devices);
129   virtual void SetWhitelistedDevices(
130       const std::vector<std::string>& whitelisted_devices);
131 
132   // Returns true if |device_name| is either not in the blacklist, or in the
133   // whitelist, depending on which list was supplied in startup settings.
134   virtual bool DeviceManagementAllowed(const std::string& device_name);
135 
136   virtual void Start();
137   virtual void Stop();
running()138   bool running() const { return running_; }
139 
140   const ProfileRefPtr& ActiveProfile() const;
141   bool IsActiveProfile(const ProfileRefPtr& profile) const;
142   bool MoveServiceToProfile(const ServiceRefPtr& to_move,
143                             const ProfileRefPtr& destination);
144   ProfileRefPtr LookupProfileByRpcIdentifier(const std::string& profile_rpcid);
145 
146   // Called via RPC call on Service (|to_set|) to set the "Profile" property.
147   virtual void SetProfileForService(const ServiceRefPtr& to_set,
148                                     const std::string& profile,
149                                     Error* error);
150 
151   virtual void RegisterDevice(const DeviceRefPtr& to_manage);
152   virtual void DeregisterDevice(const DeviceRefPtr& to_forget);
153 
154   virtual bool HasService(const ServiceRefPtr& service);
155   // Register a Service with the Manager. Manager may choose to
156   // connect to it immediately.
157   virtual void RegisterService(const ServiceRefPtr& to_manage);
158   // Deregister a Service from the Manager. Caller is responsible
159   // for disconnecting the Service before-hand.
160   virtual void DeregisterService(const ServiceRefPtr& to_forget);
161   virtual void UpdateService(const ServiceRefPtr& to_update);
162 
163   // Persists |to_update| into an appropriate profile.
164   virtual void UpdateDevice(const DeviceRefPtr& to_update);
165 
166 #if !defined(DISABLE_WIFI)
167   virtual void UpdateWiFiProvider();
168 #endif  // DISABLE_WIFI
169 
170   std::vector<DeviceRefPtr>
171       FilterByTechnology(Technology::Identifier tech) const;
172 
173   ServiceRefPtr FindService(const std::string& name);
174   RpcIdentifiers EnumerateAvailableServices(Error* error);
175 
176   // Return the complete list of services, including those that are not visible.
177   RpcIdentifiers EnumerateCompleteServices(Error* error);
178 
179   // called via RPC (e.g., from ManagerDBusAdaptor)
180   std::map<std::string, std::string> GetLoadableProfileEntriesForService(
181       const ServiceConstRefPtr& service);
182   ServiceRefPtr GetService(const KeyValueStore& args, Error* error);
183   ServiceRefPtr ConfigureService(const KeyValueStore& args, Error* error);
184   ServiceRefPtr ConfigureServiceForProfile(
185       const std::string& profile_rpcid,
186       const KeyValueStore& args,
187       Error* error);
188   ServiceRefPtr FindMatchingService(const KeyValueStore& args, Error* error);
189 
190   // Retrieve geolocation data from the Manager.
191   const std::map<std::string, GeolocationInfos>
192       &GetNetworksForGeolocation() const;
193 
194   // Called by Device when its geolocation data has been updated.
195   virtual void OnDeviceGeolocationInfoUpdated(const DeviceRefPtr& device);
196 
197   void ConnectToBestServices(Error* error);
198 
199   // Method to create connectivity report for connected services.
200   void CreateConnectivityReport(Error* error);
201 
202   // Request portal detection checks on each registered device until a portal
203   // detection attempt starts on one of them.
204   void RecheckPortal(Error* error);
205   // Request portal detection be restarted on the device connected to
206   // |service|.
207   virtual void RecheckPortalOnService(const ServiceRefPtr& service);
208 
209   virtual void RequestScan(Device::ScanType scan_type,
210                            const std::string& technology, Error* error);
211   // Configure scheduled scan for wifi devices.
212   virtual void SetSchedScan(bool enable, Error* error);
213   std::string GetTechnologyOrder();
214   virtual void SetTechnologyOrder(const std::string& order, Error* error);
215   // Set up the profile list starting with a default profile along with
216   // an (optional) list of startup profiles.
217   void InitializeProfiles();
218   // Create a profile.  This does not affect the profile stack.  Returns
219   // the RPC path of the created profile in |path|.
220   void CreateProfile(const std::string& name, std::string* path, Error* error);
221   // Pushes existing profile with name |name| onto stack of managed profiles.
222   // Returns the RPC path of the pushed profile in |path|.
223   void PushProfile(const std::string& name, std::string* path, Error* error);
224   // Insert an existing user profile with name |name| into the stack of
225   // managed profiles.  Associate |user_hash| with this profile entry.
226   // Returns the RPC path of the pushed profile in |path|.
227   void InsertUserProfile(const std::string& name,
228                          const std::string& user_hash,
229                          std::string* path,
230                          Error* error);
231   // Pops profile named |name| off the top of the stack of managed profiles.
232   void PopProfile(const std::string& name, Error* error);
233   // Remove the active profile.
234   void PopAnyProfile(Error* error);
235   // Remove all user profiles from the stack of managed profiles leaving only
236   // default profiles.
237   void PopAllUserProfiles(Error* error);
238   // Remove the underlying persistent storage for a profile.
239   void RemoveProfile(const std::string& name, Error* error);
240   // Give the ownership of the device with name |device_name| to claimer with
241   // name |claimer_name|. This will cause shill to stop managing this device.
242   virtual void ClaimDevice(const std::string& claimer_name,
243                            const std::string& interface_name,
244                            Error* error);
245   // Claimer |claimer_name| release the ownership of the device with
246   // |interface_name| back to shill. This method will set |claimer_removed|
247   // to true iff Claimer |claimer_name| is not the default claimer and no
248   // longer claims any devices.
249   virtual void ReleaseDevice(const std::string& claimer_name,
250                              const std::string& interface_name,
251                              bool* claimer_removed,
252                              Error* error);
253 #if !defined(DISABLE_WIFI) && defined(__BRILLO__)
254   // Setup an AP mode interface using WiFi driver HAL.  The driver
255   // may or may not teardown the station mode interface as a result
256   // of this call.  This behavior will be driver specific.
257   // Returns true and sets |interface_name| on success, false otherwise.
258   virtual bool SetupApModeInterface(std::string* out_interface_name,
259                                     Error* error);
260 
261   // Setup a station mode interface using WiFi driver HAL.  The driver
262   // may or may not teardown the AP mode interface as a result of this
263   // call.  This behavior will be driver specific.
264   // Returns true and sets |interface_name| on success, false otherwise.
265   virtual bool SetupStationModeInterface(std::string* out_interface_name,
266                                          Error* error);
267 
268   virtual void OnApModeSetterVanished();
269 #endif  // !DISABLE_WIFI && __BRILLO__
270 
271   // Called by a service to remove its associated configuration.  If |service|
272   // is associated with a non-ephemeral profile, this configuration entry
273   // will be removed and the manager will search for another matching profile.
274   // If the service ends up with no matching profile, it is unloaded (which
275   // may also remove the service from the manager's list, e.g. WiFi services
276   // that are not visible)..
277   void RemoveService(const ServiceRefPtr& service);
278   // Handle the event where a profile is about to remove a profile entry.
279   // Any Services that are dependent on this storage identifier will need
280   // to find new profiles.  Return true if any service has been moved to a new
281   // profile.  Any such services will have had the profile group removed from
282   // the profile.
283   virtual bool HandleProfileEntryDeletion(const ProfileRefPtr& profile,
284                                           const std::string& entry_name);
285   // Find a registered service that contains a GUID property that
286   // matches |guid|.
287   virtual ServiceRefPtr GetServiceWithGUID(const std::string& guid,
288                                            Error* error);
289   // Find a service that is both the member of |profile| and has a
290   // storage identifier that matches |entry_name|.  This function is
291   // called by the Profile in order to return a profile entry's properties.
292   virtual ServiceRefPtr GetServiceWithStorageIdentifier(
293       const ProfileRefPtr& profile,
294       const std::string& entry_name,
295       Error* error);
296   // Create a temporary service for an entry |entry_name| within |profile|.
297   // Callers must not register this service with the Manager or connect it
298   // since it was never added to the provider's service list.
299   virtual ServiceRefPtr CreateTemporaryServiceFromProfile(
300       const ProfileRefPtr& profile,
301       const std::string& entry_name,
302       Error* error);
303   // Return a reference to the Service associated with the default connection.
304   // If there is no such connection, this function returns a reference to NULL.
305   virtual ServiceRefPtr GetDefaultService() const;
306 
307   // Set enabled state of all |technology_name| devices to |enabled_state|.
308   // Persist the state to storage is |persist| is true.
309   void SetEnabledStateForTechnology(const std::string& technology_name,
310                                     bool enabled_state,
311                                     bool persist,
312                                     Error* error,
313                                     const ResultCallback& callback);
314   // Return whether a technology is marked as enabled for portal detection.
315   virtual bool IsPortalDetectionEnabled(Technology::Identifier tech);
316   // Set the start-up value for the portal detection list.  This list will
317   // be used until a value set explicitly over the control API.  Until
318   // then, we ignore but do not overwrite whatever value is stored in the
319   // profile.
320   virtual void SetStartupPortalList(const std::string& portal_list);
321 
322   // Returns true if profile |a| has been pushed on the Manager's
323   // |profiles_| stack before profile |b|.
324   virtual bool IsProfileBefore(const ProfileRefPtr& a,
325                                const ProfileRefPtr& b) const;
326 
327   // Return whether a service belongs to the ephemeral profile.
328   virtual bool IsServiceEphemeral(const ServiceConstRefPtr& service) const;
329 
330   // Return whether a Technology has any connected Services.
331   virtual bool IsTechnologyConnected(Technology::Identifier technology) const;
332 
333   // Return whether a technology is enabled for link monitoring.
334   virtual bool IsTechnologyLinkMonitorEnabled(
335       Technology::Identifier technology) const;
336 
337   // Return whether the Wake on LAN feature is enabled.
IsWakeOnLanEnabled()338   virtual bool IsWakeOnLanEnabled() const { return is_wake_on_lan_enabled_; }
339 
340   // Return whether a technology is disabled for auto-connect.
341   virtual bool IsTechnologyAutoConnectDisabled(
342       Technology::Identifier technology) const;
343 
344   // Report whether |technology| is prohibited from being enabled.
345   virtual bool IsTechnologyProhibited(Technology::Identifier technology) const;
346 
347   // Called by Profile when a |storage| completes initialization.
348   void OnProfileStorageInitialized(Profile* storage);
349 
350   // Return a Device with technology |technology| in the enabled state.
351   virtual DeviceRefPtr GetEnabledDeviceWithTechnology(
352       Technology::Identifier technology) const;
353 
354   // Return a Device with link_name |link_name| in the enabled state.
355   virtual DeviceRefPtr GetEnabledDeviceByLinkName(
356       const std::string& link_name) const;
357 
358   // Returns true if at least one connection exists, and false if there's no
359   // connected service.
360   virtual bool IsConnected() const;
361   // Returns true if at least one connection exists that have Internet
362   // connectivity, and false if there's no such service.
363   virtual bool IsOnline() const;
364   std::string CalculateState(Error* error);
365 
366   // Recalculate the |connected_state_| string and emit a singal if it has
367   // changed.
368   void RefreshConnectionState();
369 
GetPortalCheckInterval()370   virtual int GetPortalCheckInterval() const {
371     return props_.portal_check_interval_seconds;
372   }
GetPortalCheckURL()373   virtual const std::string& GetPortalCheckURL() const {
374     return props_.portal_url;
375   }
376 
device_info()377   virtual DeviceInfo* device_info() { return &device_info_; }
378 #if !defined(DISABLE_CELLULAR)
modem_info()379   virtual ModemInfo* modem_info() { return &modem_info_; }
380 #endif  // DISABLE_CELLULAR
power_manager()381   PowerManager* power_manager() const { return power_manager_.get(); }
382 #if !defined(DISABLE_WIRED_8021X)
ethernet_eap_provider()383   virtual EthernetEapProvider* ethernet_eap_provider() const {
384     return ethernet_eap_provider_.get();
385   }
386 #endif  // DISABLE_WIRED_8021X
vpn_provider()387   VPNProvider* vpn_provider() const { return vpn_provider_.get(); }
388 #if !defined(DISABLE_WIFI)
wifi_provider()389   WiFiProvider* wifi_provider() const { return wifi_provider_.get(); }
390 #endif  // DISABLE_WIFI
391 #if !defined(DISABLE_WIMAX)
wimax_provider()392   virtual WiMaxProvider* wimax_provider() { return wimax_provider_.get(); }
393 #endif  // DISABLE_WIMAX
mutable_store()394   PropertyStore* mutable_store() { return &store_; }
store()395   virtual const PropertyStore& store() const { return store_; }
run_path()396   virtual const base::FilePath& run_path() const { return run_path_; }
storage_path()397   const base::FilePath& storage_path() const { return storage_path_; }
health_checker_remote_ips()398   IPAddressStore* health_checker_remote_ips() const {
399     return health_checker_remote_ips_.get();
400   }
401 
GetArpGateway()402   bool GetArpGateway() const { return props_.arp_gateway; }
403 
GetMinimumMTU()404   virtual int GetMinimumMTU() const { return props_.minimum_mtu; }
SetMinimumMTU(const int mtu)405   virtual void SetMinimumMTU(const int mtu) { props_.minimum_mtu = mtu; }
406 
407   virtual void UpdateEnabledTechnologies();
408   virtual void UpdateUninitializedTechnologies();
409 
dhcp_properties()410   const DhcpProperties& dhcp_properties() const {
411     return *dhcp_properties_;
412   }
413 
414   // Writes the service |to_update| to persistant storage.  If the service's is
415   // ephemeral, it is moved to the current profile.
416   void SaveServiceToProfile(const ServiceRefPtr& to_update);
417 
418   // Adds a closure to be executed when ChromeOS suspends or shill terminates.
419   // |name| should be unique; otherwise, a previous closure by the same name
420   // will be replaced.  |start| will be called when RunTerminationActions() is
421   // called.  When an action completed, TerminationActionComplete() must be
422   // called.
423   void AddTerminationAction(const std::string& name,
424                             const base::Closure& start);
425 
426   // Users call this function to report the completion of an action |name|.
427   // This function should be called once for each action.
428   void TerminationActionComplete(const std::string& name);
429 
430   // Removes the action associtated with |name|.
431   void RemoveTerminationAction(const std::string& name);
432 
433   // Runs the termination actions and notifies the metrics framework
434   // that the termination actions started running, only if any termination
435   // actions have been registered. If all actions complete within
436   // |kTerminationActionsTimeoutMilliseconds|, |done_callback| is called with a
437   // value of Error::kSuccess. Otherwise, it is called with
438   // Error::kOperationTimeout.
439   //
440   // Returns true, if termination actions were run.
441   bool RunTerminationActionsAndNotifyMetrics(
442       const ResultCallback& done_callback);
443 
444   // Registers a |callback| that's invoked whenever the default service
445   // changes. Returns a unique tag that can be used to deregister the
446   // callback. A tag equal to 0 is invalid.
447   virtual int RegisterDefaultServiceCallback(const ServiceCallback& callback);
448   virtual void DeregisterDefaultServiceCallback(int tag);
449 
450 #if !defined(DISABLE_WIFI)
451   // Verifies that the destination described by certificate is valid, and that
452   // we're currently connected to that destination.  A full description of the
453   // rules being enforced is in doc/manager-api.txt.  Returns true iff all
454   // checks pass, false otherwise.  On false, error is filled with a
455   // descriptive error code and message.
456   //
457   // |certificate| is a PEM encoded x509 certificate, |public_key| is a base64
458   // encoded public half of an RSA key, |nonce| is a random string, and
459   // |signed_data| is a base64 encoded string as described in
460   // doc/manager-api.txt.
461   void VerifyDestination(const std::string& certificate,
462                          const std::string& public_key,
463                          const std::string& nonce,
464                          const std::string& signed_data,
465                          const std::string& destination_udn,
466                          const std::string& hotspot_ssid,
467                          const std::string& hotspot_bssid,
468                          const ResultBoolCallback& cb,
469                          Error* error);
470 
471   // After verifying the destination, encrypt the string data with
472   // |public_key|, the base64 encoded public half of an RSA key pair.  Returns
473   // the base64 encoded result if successful, or an empty string on failure.
474   // On failure, |error| will be filled with an appropriately descriptive
475   // message and error code.
476   void VerifyAndEncryptData(const std::string& certificate,
477                             const std::string& public_key,
478                             const std::string& nonce,
479                             const std::string& signed_data,
480                             const std::string& destination_udn,
481                             const std::string& hotspot_ssid,
482                             const std::string& hotspot_bssid,
483                             const std::string& data,
484                             const ResultStringCallback& cb,
485                             Error* error);
486 
487   // After verifying the destination, encrypt the password for |network_path|
488   // under |public_key|.  Similar to EncryptData above except that the
489   // information being encrypted is implicitly the authentication credentials
490   // of the given network.
491   void VerifyAndEncryptCredentials(const std::string& certificate,
492                                    const std::string& public_key,
493                                    const std::string& nonce,
494                                    const std::string& signed_data,
495                                    const std::string& destination_udn,
496                                    const std::string& hotspot_ssid,
497                                    const std::string& hotspot_bssid,
498                                    const std::string& network_path,
499                                    const ResultStringCallback& cb,
500                                    Error* error);
501 #endif  // DISABLE_WIFI
502 
503   // Calculate connection identifier, which is hash of salt value, gateway IP
504   // address, and gateway MAC address.
505   int CalcConnectionId(std::string gateway_ip, std::string gateway_mac);
506 
507   // Report the number of services associated with given connection
508   // |connection_id|.
509   void ReportServicesOnSameNetwork(int connection_id);
510 
511   // Running in passive mode, manager will not manage any devices (all devices
512   // are blacklisted) by default. Remote application can specify devices for
513   // shill to manage through ReleaseInterface/ClaimInterface DBus API using
514   // default claimer (with "" as claimer_name).
515   virtual void SetPassiveMode();
516 
517   // Decides whether Ethernet-like devices are treated as unknown devices
518   // if they do not indicate a driver name.
519   virtual void SetIgnoreUnknownEthernet(bool ignore);
ignore_unknown_ethernet()520   virtual bool ignore_unknown_ethernet() const {
521     return ignore_unknown_ethernet_;
522   }
523 
524   // Set the list of prepended DNS servers to |prepend_dns_servers|.
525   virtual void SetPrependDNSServers(const std::string& prepend_dns_servers);
526 
527   // Accept hostname from DHCP server for devices matching |hostname_from|.
528   virtual void SetAcceptHostnameFrom(const std::string& hostname_from);
529   virtual bool ShouldAcceptHostnameFrom(const std::string& device_name) const;
530 
531   // Set DHCPv6 enabled device list.
532   virtual void SetDHCPv6EnabledDevices(
533       const std::vector<std::string>& device_list);
534 
535   // Return true if DHCPv6 is enabled for the given device with |device_name|.
536   virtual bool IsDHCPv6EnabledForDevice(const std::string& device_name) const;
537 
538   // Filter the list of prepended DNS servers, copying only those that match
539   // |family| into |dns_servers|.  |dns_servers| is cleared, regardless of
540   // whether or not there are any addresses that match |family|.
541   virtual std::vector<std::string> FilterPrependDNSServersByFamily(
542       IPAddress::Family family) const;
543 
544   // Returns true iff |power_manager_| exists and is suspending (i.e.
545   // power_manager->suspending() is true), false otherwise.
546   virtual bool IsSuspending();
547 
548   void RecordDarkResumeWakeReason(const std::string& wake_reason);
549 
550   // Called when service's inner device changed.
551   virtual void OnInnerDevicesChanged();
552 
set_suppress_autoconnect(bool val)553   void set_suppress_autoconnect(bool val) { suppress_autoconnect_ = val; }
suppress_autoconnect()554   bool suppress_autoconnect() { return suppress_autoconnect_; }
555 
556   // Called when remote device claimer vanishes.
557   virtual void OnDeviceClaimerVanished();
558 
559  private:
560   friend class CellularTest;
561   friend class DeviceInfoTest;
562   friend class ManagerAdaptorInterface;
563   friend class ManagerTest;
564   friend class ModemInfoTest;
565   friend class ModemManagerTest;
566   friend class ServiceTest;
567   friend class VPNServiceTest;
568   friend class WiFiObjectTest;
569   friend class WiMaxProviderTest;
570 
571   FRIEND_TEST(CellularCapabilityUniversalMainTest, TerminationAction);
572   FRIEND_TEST(CellularCapabilityUniversalMainTest,
573               TerminationActionRemovedByStopModem);
574   FRIEND_TEST(CellularTest, LinkEventWontDestroyService);
575   FRIEND_TEST(DefaultProfileTest, LoadManagerDefaultProperties);
576   FRIEND_TEST(DefaultProfileTest, LoadManagerProperties);
577   FRIEND_TEST(DefaultProfileTest, Save);
578   FRIEND_TEST(DeviceTest, AcquireIPConfigWithoutSelectedService);
579   FRIEND_TEST(DeviceTest, AcquireIPConfigWithSelectedService);
580   FRIEND_TEST(DeviceTest, StartProhibited);
581   FRIEND_TEST(ManagerTest, AvailableTechnologies);
582   FRIEND_TEST(ManagerTest, ClaimBlacklistedDevice);
583   FRIEND_TEST(ManagerTest, ClaimDeviceWhenClaimerNotVerified);
584   FRIEND_TEST(ManagerTest, ClaimDeviceWithoutClaimer);
585   FRIEND_TEST(ManagerTest, ConnectedTechnologies);
586   FRIEND_TEST(ManagerTest, ConnectionStatusCheck);
587   FRIEND_TEST(ManagerTest, ConnectToBestServices);
588   FRIEND_TEST(ManagerTest, CreateConnectivityReport);
589   FRIEND_TEST(ManagerTest, DefaultTechnology);
590   FRIEND_TEST(ManagerTest, DetectMultiHomedDevices);
591   FRIEND_TEST(ManagerTest, DeviceClaimerVanishedTask);
592   FRIEND_TEST(ManagerTest, DevicePresenceStatusCheck);
593   FRIEND_TEST(ManagerTest, DeviceRegistrationAndStart);
594   FRIEND_TEST(ManagerTest, DisableTechnology);
595   FRIEND_TEST(ManagerTest, EnableTechnology);
596   FRIEND_TEST(ManagerTest, EnumerateProfiles);
597   FRIEND_TEST(ManagerTest, EnumerateServiceInnerDevices);
598   FRIEND_TEST(ManagerTest, HandleProfileEntryDeletionWithUnload);
599   FRIEND_TEST(ManagerTest, InitializeProfilesInformsProviders);
600   FRIEND_TEST(ManagerTest, InitializeProfilesHandlesDefaults);
601   FRIEND_TEST(ManagerTest, IsDefaultProfile);
602   FRIEND_TEST(ManagerTest, IsTechnologyAutoConnectDisabled);
603   FRIEND_TEST(ManagerTest, IsTechnologyProhibited);
604   FRIEND_TEST(ManagerTest, IsWifiIdle);
605   FRIEND_TEST(ManagerTest, LinkMonitorEnabled);
606   FRIEND_TEST(ManagerTest, MoveService);
607   FRIEND_TEST(ManagerTest, NotifyDefaultServiceChanged);
608   FRIEND_TEST(ManagerTest, OnApModeSetterVanished);
609   FRIEND_TEST(ManagerTest, OnDeviceClaimerAppeared);
610   FRIEND_TEST(ManagerTest, PopProfileWithUnload);
611   FRIEND_TEST(ManagerTest, RegisterKnownService);
612   FRIEND_TEST(ManagerTest, RegisterUnknownService);
613   FRIEND_TEST(ManagerTest, ReleaseBlacklistedDevice);
614   FRIEND_TEST(ManagerTest, ReleaseDevice);
615   FRIEND_TEST(ManagerTest, RunTerminationActions);
616   FRIEND_TEST(ManagerTest, ServiceRegistration);
617   FRIEND_TEST(ManagerTest, SetupApModeInterface);
618   FRIEND_TEST(ManagerTest, SetupStationModeInterface);
619   FRIEND_TEST(ManagerTest, SortServicesWithConnection);
620   FRIEND_TEST(ManagerTest, StartupPortalList);
621   FRIEND_TEST(ServiceTest, IsAutoConnectable);
622 
623   struct DeviceClaim {
DeviceClaimDeviceClaim624     DeviceClaim() {}
DeviceClaimDeviceClaim625     DeviceClaim(const std::string& in_device_name,
626                 const ResultCallback& in_result_callback)
627         : device_name(in_device_name),
628           result_callback(in_result_callback) {}
629     std::string device_name;
630     ResultCallback result_callback;
631   };
632 
633   static const char kErrorNoDevice[];
634   static const char kErrorTypeRequired[];
635   static const char kErrorUnsupportedServiceType[];
636 
637   // Technologies to probe for.
638   static const char* kProbeTechnologies[];
639 
640   // Name of the default claimer.
641   static const char kDefaultClaimerName[];
642 
643   // Timeout interval for probing various device status, and report them to
644   // UMA stats.
645   static const int kDeviceStatusCheckIntervalMilliseconds;
646   // Time to wait for termination actions to complete.
647   static const int kTerminationActionsTimeoutMilliseconds;
648 
649   void AutoConnect();
650   std::vector<std::string> AvailableTechnologies(Error* error);
651   std::vector<std::string> ConnectedTechnologies(Error* error);
652   std::string DefaultTechnology(Error* error);
653   std::vector<std::string> EnabledTechnologies(Error* error);
654   std::vector<std::string> UninitializedTechnologies(Error* error);
655   RpcIdentifiers EnumerateDevices(Error* error);
656   RpcIdentifiers EnumerateProfiles(Error* error);
657   RpcIdentifiers EnumerateWatchedServices(Error* error);
658   std::string GetActiveProfileRpcIdentifier(Error* error);
659   std::string GetCheckPortalList(Error* error);
660   RpcIdentifier GetDefaultServiceRpcIdentifier(Error* error);
661   std::string GetIgnoredDNSSearchPaths(Error* error);
662   ServiceRefPtr GetServiceInner(const KeyValueStore& args, Error* error);
663   bool SetCheckPortalList(const std::string& portal_list, Error* error);
664   bool SetIgnoredDNSSearchPaths(const std::string& ignored_paths, Error* error);
665   void EmitDefaultService();
666   bool IsTechnologyInList(const std::string& technology_list,
667                           Technology::Identifier tech) const;
668   void EmitDeviceProperties();
669 #if !defined(DISABLE_WIFI)
670   bool SetDisableWiFiVHT(const bool& disable_wifi_vht, Error* error);
671   bool GetDisableWiFiVHT(Error* error);
672 #endif  // DISABLE_WIFI
673   bool SetProhibitedTechnologies(const std::string& prohibited_technologies,
674                                  Error* error);
675   std::string GetProhibitedTechnologies(Error* error);
676   void OnTechnologyProhibited(Technology::Identifier technology,
677                               const Error& error);
678 
679   // For every device instance that is sharing the same connectivity with
680   // another device, enable the multi-home flag.
681   void DetectMultiHomedDevices();
682 
683   // Unload a service while iterating through |services_|.  Returns true if
684   // service was erased (which means the caller loop should not increment
685   // |service_iterator|), false otherwise (meaning the caller should
686   // increment |service_iterator|).
687   bool UnloadService(std::vector<ServiceRefPtr>::iterator* service_iterator);
688 
689   // Load Manager default properties from |profile|.
690   void LoadProperties(const scoped_refptr<DefaultProfile>& profile);
691 
692   // Configure the device with profile data from all current profiles.
693   void LoadDeviceFromProfiles(const DeviceRefPtr& device);
694 
695   void HelpRegisterConstDerivedRpcIdentifier(
696       const std::string& name,
697       RpcIdentifier(Manager::*get)(Error*));
698   void HelpRegisterConstDerivedRpcIdentifiers(
699       const std::string& name,
700       RpcIdentifiers(Manager::*get)(Error*));
701   void HelpRegisterDerivedString(
702       const std::string& name,
703       std::string(Manager::*get)(Error* error),
704       bool(Manager::*set)(const std::string&, Error*));
705   void HelpRegisterConstDerivedStrings(
706       const std::string& name,
707       Strings(Manager::*get)(Error*));
708   void HelpRegisterDerivedBool(
709       const std::string& name,
710       bool(Manager::*get)(Error* error),
711       bool(Manager::*set)(const bool& value, Error* error));
712 
713   bool HasProfile(const Profile::Identifier& ident);
714   void PushProfileInternal(const Profile::Identifier& ident,
715                            std::string* path,
716                            Error* error);
717   void PopProfileInternal();
718   void OnProfilesChanged();
719 
720   void SortServices();
721   void SortServicesTask();
722   void DeviceStatusCheckTask();
723   void ConnectionStatusCheck();
724   void DevicePresenceStatusCheck();
725 
726   bool MatchProfileWithService(const ServiceRefPtr& service);
727 
728   // Sets the profile of |service| to |profile|, without notifying its
729   // previous profile.  Configures a |service| with |args|, then saves
730   // the resulting configuration to |profile|.  This method is useful
731   // when copying a service configuration from one profile to another,
732   // or writing a newly created service config to a specific profile.
733   static void SetupServiceInProfile(ServiceRefPtr service,
734                                     ProfileRefPtr profile,
735                                     const KeyValueStore& args,
736                                     Error* error);
737 
738   // For each technology present, connect to the "best" service available,
739   // as determined by sorting all services independent of their current state.
740   void ConnectToBestServicesTask();
741 
742   void NotifyDefaultServiceChanged(const ServiceRefPtr& service);
743 
744   // Runs the termination actions.  If all actions complete within
745   // |kTerminationActionsTimeoutMilliseconds|, |done_callback| is called with a
746   // value of Error::kSuccess.  Otherwise, it is called with
747   // Error::kOperationTimeout.
748   void RunTerminationActions(const ResultCallback& done_callback);
749 
750   // Called when the system is about to be suspended.  Each call will be
751   // followed by a call to OnSuspendDone().
752   void OnSuspendImminent();
753 
754   // Called when the system has completed a suspend attempt (possibly without
755   // actually suspending, in the event of the user canceling the attempt).
756   void OnSuspendDone();
757 
758   // Called when the system is entering a dark resume phase (and hence a dark
759   // suspend is imminent).
760   void OnDarkSuspendImminent();
761 
762   void OnSuspendActionsComplete(const Error& error);
763   void OnDarkResumeActionsComplete(const Error& error);
764 
765 #if !defined(DISABLE_WIFI)
766   void VerifyToEncryptLink(std::string public_key, std::string data,
767                            ResultStringCallback cb, const Error& error,
768                            bool success);
769 #endif  // DISABLE_WIFI
770 
771   // Return true if wifi device is enabled with no existing connection (pending
772   // or connected).
773   bool IsWifiIdle();
774 
775   // For unit testing.
set_metrics(Metrics * metrics)776   void set_metrics(Metrics* metrics) { metrics_ = metrics; }
777   void UpdateProviderMapping();
778 
779   // Used by tests to set a mock PowerManager.  Takes ownership of
780   // power_manager.
set_power_manager(PowerManager * power_manager)781   void set_power_manager(PowerManager* power_manager) {
782     power_manager_.reset(power_manager);
783   }
784 
785   DeviceRefPtr GetDeviceConnectedToService(ServiceRefPtr service);
786 
787   void DeregisterDeviceByLinkName(const std::string& link_name);
788 
789   // Returns the names of all of the devices that have been claimed by the
790   // current DeviceClaimer.  Returns an empty vector if no DeviceClaimer is set.
791   std::vector<std::string> ClaimedDevices(Error* error);
792 
793   EventDispatcher* dispatcher_;
794   const base::FilePath run_path_;
795   const base::FilePath storage_path_;
796   const base::FilePath user_storage_path_;
797   base::FilePath user_profile_list_path_;  // Changed in tests.
798   std::unique_ptr<ManagerAdaptorInterface> adaptor_;
799   DeviceInfo device_info_;
800 #if !defined(DISABLE_CELLULAR)
801   ModemInfo modem_info_;
802 #endif  // DISABLE_CELLULAR
803 #if !defined(DISABLE_WIRED_8021X)
804   std::unique_ptr<EthernetEapProvider> ethernet_eap_provider_;
805 #endif  // DISABLE_WIRED_8021X
806   std::unique_ptr<VPNProvider> vpn_provider_;
807 #if !defined(DISABLE_WIFI)
808   std::unique_ptr<WiFiProvider> wifi_provider_;
809 #if defined(__BRILLO__)
810   WiFiDriverHal* wifi_driver_hal_;
811 #endif  // __BRILLO__
812 #endif  // DISABLE_WIFI
813 #if !defined(DISABLE_WIMAX)
814   std::unique_ptr<WiMaxProvider> wimax_provider_;
815 #endif  // DISABLE_WIMAX
816   // Hold pointer to singleton Resolver instance for testing purposes.
817   Resolver* resolver_;
818   bool running_;
819   // Used to facilitate unit tests which can't use RPC.
820   bool connect_profiles_to_rpc_;
821   std::vector<DeviceRefPtr> devices_;
822   // We store Services in a vector, because we want to keep them sorted.
823   // Services that are connected appear first in the vector.  See
824   // Service::Compare() for details of the sorting criteria.
825   std::vector<ServiceRefPtr> services_;
826   // Map of technologies to Provider instances.  These pointers are owned
827   // by the respective scoped_reptr objects that are held over the lifetime
828   // of the Manager object.
829   std::map<Technology::Identifier, ProviderInterface*> providers_;
830   // List of startup profile names to push on the profile stack on startup.
831   std::vector<ProfileRefPtr> profiles_;
832   ProfileRefPtr ephemeral_profile_;
833   ControlInterface* control_interface_;
834   Metrics* metrics_;
835   std::unique_ptr<PowerManager> power_manager_;
836   std::unique_ptr<Upstart> upstart_;
837 
838   // The priority order of technologies
839   std::vector<Technology::Identifier> technology_order_;
840 
841   // This is the last Service RPC Identifier for which we emitted a
842   // "DefaultService" signal for.
843   RpcIdentifier default_service_rpc_identifier_;
844 
845   // Manager can be optionally configured with a list of technologies to
846   // do portal detection on at startup.  We need to keep track of that list
847   // as well as a flag that tells us whether we should continue using it
848   // instead of the configured portal list.
849   std::string startup_portal_list_;
850   bool use_startup_portal_list_;
851 
852   // Properties to be get/set via PropertyStore calls.
853   Properties props_;
854   PropertyStore store_;
855 
856   // Accept hostname supplied by the DHCP server from the specified devices.
857   // eg. eth0 or eth*
858   std::string accept_hostname_from_;
859 
860   base::CancelableClosure sort_services_task_;
861 
862   // Task for periodically checking various device status.
863   base::CancelableClosure device_status_check_task_;
864 
865   // TODO(petkov): Currently this handles both terminate and suspend
866   // actions. Rename all relevant identifiers to capture this.
867   HookTable termination_actions_;
868 
869   // Is a suspend delay currently registered with the power manager?
870   bool suspend_delay_registered_;
871 
872   // Whether Wake on LAN should be enabled for all Ethernet devices.
873   bool is_wake_on_lan_enabled_;
874 
875   // Whether to ignore Ethernet-like devices that don't have an assigned driver.
876   bool ignore_unknown_ethernet_;
877 
878   // Maps tags to callbacks for monitoring default service changes.
879   std::map<int, ServiceCallback> default_service_callbacks_;
880   int default_service_callback_tag_;
881 
882   // Delegate to handle destination verification operations for the manager.
883   std::unique_ptr<CryptoUtilProxy> crypto_util_proxy_;
884 
885   // Stores IP addresses of some remote hosts that accept port 80 TCP
886   // connections. ConnectionHealthChecker uses these IPs.
887   // The store resides in Manager so that it persists across Device reset.
888   std::unique_ptr<IPAddressStore> health_checker_remote_ips_;
889 
890   // Stores the most recent copy of geolocation information for each
891   // technology type.
892   std::map<std::string, GeolocationInfos> networks_for_geolocation_;
893 
894   // Stores the state of the highest ranked connected service.
895   std::string connection_state_;
896 
897   // Stores the most recent state of all watched services.
898   std::map<std::string, Service::ConnectState> watched_service_states_;
899 
900   // Device claimer is a remote application/service that claim/release devices
901   // from/to shill. To reduce complexity, only allow one device claimer at a
902   // time.
903   std::unique_ptr<DeviceClaimer> device_claimer_;
904 
905   // When true, suppresses autoconnects in Manager::AutoConnect.
906   bool suppress_autoconnect_;
907 
908   // Whether any of the services is in connected state or not.
909   bool is_connected_state_;
910 
911   // List of blacklisted devices specified from command line.
912   std::vector<std::string> blacklisted_devices_;
913 
914   // List of whitelisted devices specified from command line.
915   std::vector<std::string> whitelisted_devices_;
916 
917   // List of DHCPv6 enabled devices.
918   std::vector<std::string> dhcpv6_enabled_devices_;
919 
920   // DhcpProperties stored for the default profile.
921   std::unique_ptr<DhcpProperties> dhcp_properties_;
922 
923   DISALLOW_COPY_AND_ASSIGN(Manager);
924 };
925 
926 }  // namespace shill
927 
928 #endif  // SHILL_MANAGER_H_
929