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_DEVICE_H_
18 #define SHILL_DEVICE_H_
19 
20 #include <memory>
21 #include <set>
22 #include <string>
23 #include <vector>
24 
25 #include <base/macros.h>
26 #include <base/memory/ref_counted.h>
27 #include <base/memory/weak_ptr.h>
28 #include <gtest/gtest_prod.h>  // for FRIEND_TEST
29 
30 #include "shill/adaptor_interfaces.h"
31 #include "shill/callbacks.h"
32 #include "shill/connection_diagnostics.h"
33 #include "shill/connection_tester.h"
34 #include "shill/connectivity_trial.h"
35 #include "shill/dns_server_tester.h"
36 #include "shill/event_dispatcher.h"
37 #include "shill/ipconfig.h"
38 #include "shill/net/ip_address.h"
39 #include "shill/net/shill_time.h"
40 #include "shill/portal_detector.h"
41 #include "shill/property_store.h"
42 #include "shill/refptr_types.h"
43 #include "shill/service.h"
44 #include "shill/technology.h"
45 
46 namespace shill {
47 
48 class ControlInterface;
49 class DHCPProvider;
50 class DeviceAdaptorInterface;
51 class Endpoint;
52 class Error;
53 class EventDispatcher;
54 class GeolocationInfo;
55 class LinkMonitor;
56 class Manager;
57 class Metrics;
58 class RTNLHandler;
59 class TrafficMonitor;
60 
61 // Device superclass.  Individual network interfaces types will inherit from
62 // this class.
63 class Device : public base::RefCounted<Device> {
64  public:
65   // Progressively scanning for access points (APs) is done with multiple scans,
66   // each containing a group of channels.  The scans are performed in order of
67   // decreasing likelihood of connecting on one of the channels in a group
68   // (the number of channels in a group is a matter for system tuning).  Fully
69   // scanning for APs does a complete scan of all the channels in a single scan.
70   // Progressive scanning is supported for wifi devices; technologies that
71   // support scan but don't support progressive scan will always perform a full
72   // scan, regardless of the requested scan type.
73   enum ScanType { kProgressiveScan, kFullScan };
74 
75   // A constructor for the Device object
76   Device(ControlInterface* control_interface,
77          EventDispatcher* dispatcher,
78          Metrics* metrics,
79          Manager* manager,
80          const std::string& link_name,
81          const std::string& address,
82          int interface_index,
83          Technology::Identifier technology);
84 
85   // Initialize type-specific network interface properties.
86   virtual void Initialize();
87 
88   // Enable or disable the device. This is a convenience method for
89   // cases where we want to SetEnabledNonPersistent, but don't care
90   // about the results.
91   virtual void SetEnabled(bool enable);
92   // Enable or disable the device. Unlike SetEnabledPersistent, it does not
93   // save the setting in the profile.
94   //
95   // TODO(quiche): Replace both of the next two methods with calls to
96   // SetEnabledChecked.
97   virtual void SetEnabledNonPersistent(bool enable,
98                                        Error* error,
99                                        const ResultCallback& callback);
100   // Enable or disable the device, and save the setting in the profile.
101   // The setting is persisted before the enable or disable operation
102   // starts, so that even if it fails, the user's intent is still recorded
103   // for the next time shill restarts.
104   virtual void SetEnabledPersistent(bool enable,
105                                     Error* error,
106                                     const ResultCallback& callback);
107   // Enable or disable the Device, depending on |enable|.
108   // Save the new setting to the profile, if |persist| is true.
109   // Report synchronous errors using |error|, and asynchronous completion
110   // with |callback|.
111   virtual void SetEnabledChecked(bool enable,
112                                  bool persist,
113                                  Error* error,
114                                  const ResultCallback& callback);
115   // Similar to SetEnabledChecked, but without sanity checking, and
116   // without saving the new value of |enable| to the profile. If you
117   // are sane (i.e. not Cellular), you should use
118   // SetEnabledChecked instead.
119   virtual void SetEnabledUnchecked(bool enable,
120                                    Error* error,
121                                    const ResultCallback& callback);
122 
123   // Returns true if the underlying device reports that it is already enabled.
124   // Used when the device is registered with the Manager, so that shill can
125   // sync its state/ with the true state of the device. The default is to
126   // report false.
127   virtual bool IsUnderlyingDeviceEnabled() const;
128 
129   virtual void LinkEvent(unsigned flags, unsigned change);
130 
131   // The default implementation sets |error| to kNotSupported.
132   virtual void Scan(ScanType scan_type, Error* error,
133                     const std::string& reason);
134   // The default implementation sets |error| to kNotSupported.
135   virtual void SetSchedScan(bool enable, Error* error);
136   virtual void RegisterOnNetwork(const std::string& network_id, Error* error,
137                                  const ResultCallback& callback);
138   virtual void RequirePIN(const std::string& pin, bool require,
139                           Error* error, const ResultCallback& callback);
140   virtual void EnterPIN(const std::string& pin,
141                         Error* error, const ResultCallback& callback);
142   virtual void UnblockPIN(const std::string& unblock_code,
143                           const std::string& pin,
144                           Error* error, const ResultCallback& callback);
145   virtual void ChangePIN(const std::string& old_pin,
146                          const std::string& new_pin,
147                          Error* error, const ResultCallback& callback);
148   virtual void Reset(Error* error, const ResultCallback& callback);
149 
150   virtual void SetCarrier(const std::string& carrier,
151                           Error* error, const ResultCallback& callback);
152 
153   // Returns true if IPv6 is allowed and should be enabled when the device
154   // tries to acquire an IP configuration. The default implementation allows
155   // IPv6, which can be overridden by a derived class.
156   virtual bool IsIPv6Allowed() const;
157 
158   virtual void DisableIPv6();
159   virtual void EnableIPv6();
160   virtual void EnableIPv6Privacy();
161 
162   // Returns true if the selected service on the device (if any) is connected.
163   // Returns false if there is no selected service, or if the selected service
164   // is not connected.
165   bool IsConnected() const;
166 
167   // Called by Device so that subclasses can run hooks on the selected service
168   // getting an IP.  Subclasses should call up to the parent first.
169   virtual void OnConnected();
170 
171   // Called by the Connection so that the Device can update the service sorting
172   // after one connection is bound to another.
173   virtual void OnConnectionUpdated();
174 
175   // Returns true if the selected service on the device (if any) is connected
176   // and matches the passed-in argument |service|.  Returns false if there is
177   // no connected service, or if it does not match |service|.
178   virtual bool IsConnectedToService(const ServiceRefPtr& service) const;
179 
180   // Returns true if the DHCP parameters provided indicate that we are tethered
181   // to a mobile device.
182   virtual bool IsConnectedViaTether() const;
183 
184   // Restart the portal detection process on a connected device.  This is
185   // useful if the properties on the connected service have changed in a
186   // way that may affect the decision to run portal detection at all.
187   // Returns true if portal detection was started.
188   virtual bool RestartPortalDetection();
189 
190   // Called by the manager to start a single connectivity test.  This is used to
191   // log connection state triggered by a user feedback log request.
192   virtual bool StartConnectivityTest();
193 
194   // Get receive and transmit byte counters.
195   virtual uint64_t GetReceiveByteCount();
196   virtual uint64_t GetTransmitByteCount();
197 
198   // Perform a TDLS |operation| on the underlying device, with respect
199   // to a given |peer|.  The string returned is empty for any operation
200   // other than kTDLSOperationStatus, which returns the state of the
201   // TDLS link with |peer|.  This method is only valid for WiFi devices,
202   // but needs to be declared here since it is part of the Device RPC
203   // API.
204   virtual std::string PerformTDLSOperation(const std::string& operation,
205                                            const std::string& peer,
206                                            Error* error);
207 
208   // Reset the persisted byte counters associated with the device.
209   void ResetByteCounters();
210 
211   // Requests that portal detection be done, if this device has the default
212   // connection.  Returns true if portal detection was started.
213   virtual bool RequestPortalDetection();
214 
215   std::string GetRpcIdentifier() const;
216   std::string GetStorageIdentifier() const;
217 
218   // Returns a list of Geolocation objects. Each object is multiple
219   // key-value pairs representing one entity that can be used for
220   // Geolocation.
221   virtual std::vector<GeolocationInfo> GetGeolocationObjects() const;
222 
223   // Enable or disable this interface to receive packets even if it is not
224   // the default connection.  This is useful in limited situations such as
225   // during portal detection.
226   virtual void SetLooseRouting(bool is_loose_routing);
227 
228   // Enable or disable same-net multi-home support for this interface.  When
229   // enabled, ARP filtering is enabled in order to avoid the "ARP Flux"
230   // effect where peers may end up with inaccurate IP address mappings due to
231   // the default Linux ARP transmit / reply behavior.  See
232   // http://linux-ip.net/html/ether-arp.html for more details on this effect.
233   virtual void SetIsMultiHomed(bool is_multi_homed);
234 
address()235   const std::string& address() const { return hardware_address_; }
link_name()236   const std::string& link_name() const { return link_name_; }
interface_index()237   int interface_index() const { return interface_index_; }
connection()238   virtual const ConnectionRefPtr& connection() const { return connection_; }
enabled()239   bool enabled() const { return enabled_; }
enabled_persistent()240   bool enabled_persistent() const { return enabled_persistent_; }
technology()241   virtual Technology::Identifier technology() const { return technology_; }
242   std::string GetTechnologyString(Error* error);
243 
ipconfig()244   virtual const IPConfigRefPtr& ipconfig() const { return ipconfig_; }
ip6config()245   virtual const IPConfigRefPtr& ip6config() const { return ip6config_; }
dhcpv6_config()246   virtual const IPConfigRefPtr& dhcpv6_config() const { return dhcpv6_config_; }
set_ipconfig(const IPConfigRefPtr & config)247   void set_ipconfig(const IPConfigRefPtr& config) { ipconfig_ = config; }
248 
249   const std::string& FriendlyName() const;
250 
251   // Returns a string that is guaranteed to uniquely identify this Device
252   // instance.
253   const std::string& UniqueName() const;
254 
mutable_store()255   PropertyStore* mutable_store() { return &store_; }
store()256   const PropertyStore& store() const { return store_; }
rtnl_handler()257   RTNLHandler* rtnl_handler() { return rtnl_handler_; }
running()258   bool running() const { return running_; }
259 
dispatcher()260   EventDispatcher* dispatcher() const { return dispatcher_; }
261 
262   // Load configuration for the device from |storage|.  This may include
263   // instantiating non-visible services for which configuration has been
264   // stored.
265   virtual bool Load(StoreInterface* storage);
266 
267   // Save configuration for the device to |storage|.
268   virtual bool Save(StoreInterface* storage);
269 
set_dhcp_provider(DHCPProvider * provider)270   void set_dhcp_provider(DHCPProvider* provider) { dhcp_provider_ = provider; }
271 
adaptor()272   DeviceAdaptorInterface* adaptor() const { return adaptor_.get(); }
273 
274   // Suspend event handler. Called by Manager before the system
275   // suspends. This handler, along with any other suspend handlers,
276   // will have Manager::kTerminationActionsTimeoutMilliseconds to
277   // execute before the system enters the suspend state. |callback|
278   // must be invoked after all synchronous and/or asynchronous actions
279   // this function performs complete. Code that needs to run on exit should use
280   // Manager::AddTerminationAction, rather than OnBeforeSuspend.
281   //
282   // The default implementation invokes the |callback| immediately, since
283   // there is nothing to be done in the general case.
284   virtual void OnBeforeSuspend(const ResultCallback& callback);
285 
286   // Resume event handler. Called by Manager as the system resumes.
287   // The base class implementation takes care of renewing a DHCP lease
288   // (if necessary). Derived classes may implement any technology
289   // specific requirements by overriding, but should include a call to
290   // the base class implementation.
291   virtual void OnAfterResume();
292 
293   // This method is invoked when the system resumes from suspend temporarily in
294   // the "dark resume" state. The system will reenter suspend in
295   // Manager::kTerminationActionsTimeoutMilliseconds. |callback| must be invoked
296   // after all synchronous and/or asynchronous actions this function performs
297   // and/or posts complete.
298   //
299   // The default implementation invokes the |callback| immediately, since
300   // there is nothing to be done in the general case.
301   virtual void OnDarkResume(const ResultCallback& callback);
302 
303   // Destroy the lease, if any, with this |name|.
304   // Called by the service during Unload() as part of the cleanup sequence.
305   virtual void DestroyIPConfigLease(const std::string& name);
306 
307   // Called by DeviceInfo when the kernel adds or removes a globally-scoped
308   // IPv6 address from this interface.
309   virtual void OnIPv6AddressChanged();
310 
311   // Called by DeviceInfo when the kernel receives a update for IPv6 DNS server
312   // addresses from this interface.
313   virtual void OnIPv6DnsServerAddressesChanged();
314 
315   // Called when link becomes unreliable (multiple link monitor failures
316   // detected in short period of time).
317   virtual void OnUnreliableLink();
318 
319   // Called when link becomes reliable (no link failures in a predefined period
320   // of time).
321   virtual void OnReliableLink();
322 
323   // Program a rule into the NIC to wake the system from suspend upon receiving
324   // packets from |ip_endpoint|. |error| indicates the result of the
325   // operation.
326   virtual void AddWakeOnPacketConnection(const std::string& ip_endpoint,
327                                          Error* error);
328   // Removes a rule previously programmed into the NIC to wake the system from
329   // suspend upon receiving packets from |ip_endpoint|. |error| indicates the
330   // result of the operation.
331   virtual void RemoveWakeOnPacketConnection(const std::string& ip_endpoint,
332                                             Error* error);
333   // Removes all wake-on-packet rules programmed into the NIC. |error| indicates
334   // the result of the operation.
335   virtual void RemoveAllWakeOnPacketConnections(Error* error);
336 
337   // Initiate renewal of existing DHCP lease.
338   void RenewDHCPLease();
339 
340   // Resolve the |input| string into a MAC address for a peer local to this
341   // device. This could be a trivial operation if the |input| is already a MAC
342   // address, or could involve an ARP table lookup.  Returns true and populates
343   // |output| if the resolution completes, otherwise returns false and
344   // populates |error|.
345   virtual bool ResolvePeerMacAddress(const std::string& input,
346                                      std::string* output,
347                                      Error* error);
348 
349   // Creates a byte vector from a colon-separated hardware address string.
350   static std::vector<uint8_t> MakeHardwareAddressFromString(
351       const std::string& address_string);
352 
353   // Creates a colon-separated hardware address string from a byte vector.
354   static std::string MakeStringFromHardwareAddress(
355       const std::vector<uint8_t>& address_data);
356 
357   // Request the WiFi device to roam to AP with |addr|.
358   // This call will send Roam command to wpa_supplicant.
359   virtual bool RequestRoam(const std::string& addr, Error* error);
360 
361  protected:
362   friend class base::RefCounted<Device>;
363   friend class DeviceHealthCheckerTest;
364   FRIEND_TEST(CellularServiceTest, IsAutoConnectable);
365   FRIEND_TEST(CellularTest, EnableTrafficMonitor);
366   FRIEND_TEST(CellularTest, ModemStateChangeDisable);
367   FRIEND_TEST(CellularTest, UseNoArpGateway);
368   FRIEND_TEST(DeviceHealthCheckerTest, HealthCheckerPersistsAcrossDeviceReset);
369   FRIEND_TEST(DeviceHealthCheckerTest, RequestConnectionHealthCheck);
370   FRIEND_TEST(DeviceHealthCheckerTest, SetupHealthChecker);
371   FRIEND_TEST(DevicePortalDetectionTest, RequestStartConnectivityTest);
372   FRIEND_TEST(DeviceTest, AcquireIPConfigWithoutSelectedService);
373   FRIEND_TEST(DeviceTest, AcquireIPConfigWithSelectedService);
374   FRIEND_TEST(DeviceTest, AvailableIPConfigs);
375   FRIEND_TEST(DeviceTest, DestroyIPConfig);
376   FRIEND_TEST(DeviceTest, DestroyIPConfigNULL);
377   FRIEND_TEST(DeviceTest, ConfigWithMinimumMTU);
378   FRIEND_TEST(DeviceTest, EnableIPv6);
379   FRIEND_TEST(DeviceTest, GetProperties);
380   FRIEND_TEST(DeviceTest, IPConfigUpdatedFailureWithIPv6Config);
381   FRIEND_TEST(DeviceTest, IPConfigUpdatedFailureWithIPv6Connection);
382   FRIEND_TEST(DeviceTest, IsConnectedViaTether);
383   FRIEND_TEST(DeviceTest, LinkMonitorFailure);
384   FRIEND_TEST(DeviceTest, Load);
385   FRIEND_TEST(DeviceTest, OnDHCPv6ConfigExpired);
386   FRIEND_TEST(DeviceTest, OnDHCPv6ConfigFailed);
387   FRIEND_TEST(DeviceTest, OnDHCPv6ConfigUpdated);
388   FRIEND_TEST(DeviceTest, OnIPv6AddressChanged);
389   FRIEND_TEST(DeviceTest, OnIPv6ConfigurationCompleted);
390   FRIEND_TEST(DeviceTest, OnIPv6DnsServerAddressesChanged);
391   FRIEND_TEST(DeviceTest,
392               OnIPv6DnsServerAddressesChanged_LeaseExpirationUpdated);
393   FRIEND_TEST(DeviceTest, PrependIPv4DNSServers);
394   FRIEND_TEST(DeviceTest, PrependIPv6DNSServers);
395   FRIEND_TEST(DeviceTest, Save);
396   FRIEND_TEST(DeviceTest, SelectedService);
397   FRIEND_TEST(DeviceTest, SetEnabledNonPersistent);
398   FRIEND_TEST(DeviceTest, SetEnabledPersistent);
399   FRIEND_TEST(DeviceTest, SetServiceConnectedState);
400   FRIEND_TEST(DeviceTest, ShouldUseArpGateway);
401   FRIEND_TEST(DeviceTest, Start);
402   FRIEND_TEST(DeviceTest, StartTrafficMonitor);
403   FRIEND_TEST(DeviceTest, Stop);
404   FRIEND_TEST(DeviceTest, StopTrafficMonitor);
405   FRIEND_TEST(ManagerTest, ConnectedTechnologies);
406   FRIEND_TEST(ManagerTest, DefaultTechnology);
407   FRIEND_TEST(ManagerTest, DeviceRegistrationAndStart);
408   FRIEND_TEST(ManagerTest, GetEnabledDeviceWithTechnology);
409   FRIEND_TEST(ManagerTest, SetEnabledStateForTechnology);
410   FRIEND_TEST(ManagerTest, GetEnabledDeviceByLinkName);
411   FRIEND_TEST(PPPDeviceTest, UpdateIPConfigFromPPP);
412   FRIEND_TEST(WiFiMainTest, Connect);
413   FRIEND_TEST(WiFiMainTest, UseArpGateway);
414   FRIEND_TEST(WiMaxTest, ConnectTimeout);
415   FRIEND_TEST(WiMaxTest, UseNoArpGateway);
416 
417   virtual ~Device();
418 
419   // Each device must implement this method to do the work needed to
420   // enable the device to operate for establishing network connections.
421   // The |error| argument, if not nullptr,
422   // will refer to an Error that starts out with the value
423   // Error::kOperationInitiated. This reflects the assumption that
424   // enable (and disable) operations will usually be non-blocking,
425   // and their completion will be indicated by means of an asynchronous
426   // reply sometime later. There are two circumstances in which a
427   // device's Start() method may overwrite |error|:
428   //
429   // 1. If an early failure is detected, such that the non-blocking
430   //    part of the operation never takes place, then |error| should
431   //    be set to the appropriate value corresponding to the type
432   //    of failure. This is the "immediate failure" case.
433   // 2. If the device is enabled without performing any non-blocking
434   //    steps, then |error| should be Reset, i.e., its value set
435   //    to Error::kSuccess. This is the "immediate success" case.
436   //
437   // In these two cases, because completion is immediate, |callback|
438   // is not used. If neither of these two conditions holds, then |error|
439   // should not be modified, and |callback| should be passed to the
440   // method that will initiate the non-blocking operation.
441   virtual void Start(Error* error,
442                      const EnabledStateChangedCallback& callback) = 0;
443 
444   // Each device must implement this method to do the work needed to
445   // disable the device, i.e., clear any running state, and make the
446   // device no longer capable of establishing network connections.
447   // The discussion for Start() regarding the use of |error| and
448   // |callback| apply to Stop() as well.
449   virtual void Stop(Error* error,
450                     const EnabledStateChangedCallback& callback) = 0;
451 
452   // The EnabledStateChangedCallback that gets passed to the device's
453   // Start() and Stop() methods is bound to this method. |callback|
454   // is the callback that was passed to SetEnabled().
455   void OnEnabledStateChanged(const ResultCallback& callback,
456                              const Error& error);
457 
458   // Drops the currently selected service along with its IP configuration and
459   // connection, if any.
460   virtual void DropConnection();
461 
462   // If there's an IP configuration in |ipconfig_|, releases the IP address and
463   // destroys the configuration instance.
464   void DestroyIPConfig();
465 
466   // Creates a new DHCP IP configuration instance, stores it in |ipconfig_| and
467   // requests a new IP configuration.  Saves the DHCP lease to the generic
468   // lease filename based on the interface name.  Registers a callback to
469   // IPConfigUpdatedCallback on IP configuration changes. Returns true if the IP
470   // request was successfully sent.
471   bool AcquireIPConfig();
472 
473   // Creates a new DHCP IP configuration instance, stores it in |ipconfig_| and
474   // requests a new IP configuration.  Saves the DHCP lease to a filename
475   // based on the passed-in |lease_name|.  Registers a callback to
476   // IPConfigUpdatedCallback on IP configuration changes. Returns true if the IP
477   // request was successfully sent.
478   bool AcquireIPConfigWithLeaseName(const std::string& lease_name);
479 
480 #ifndef DISABLE_DHCPV6
481   // Creates a new DHCPv6 configuration instances, stores it in
482   // |dhcpv6_config_| and requests a new configuration.  Saves the DHCPv6
483   // lease to a filename based on the passed-in |lease_name|.
484   // The acquired configurations will not be used to setup a connection
485   // for the device.
486   bool AcquireIPv6ConfigWithLeaseName(const std::string& lease_name);
487 #endif
488 
489   // Assigns the IP configuration |properties| to |ipconfig_|.
490   void AssignIPConfig(const IPConfig::Properties& properties);
491 
492   // Callback invoked on successful IP configuration updates.
493   virtual void OnIPConfigUpdated(const IPConfigRefPtr& ipconfig,
494                                  bool new_lease_acquired);
495 
496   // Called when IPv6 configuration changes.
497   virtual void OnIPv6ConfigUpdated();
498 
499   // Callback invoked on IP configuration failures.
500   void OnIPConfigFailed(const IPConfigRefPtr& ipconfig);
501 
502   // Callback invoked when "Refresh" is invoked on an IPConfig.  This usually
503   // signals a change in static IP parameters.
504   void OnIPConfigRefreshed(const IPConfigRefPtr& ipconfig);
505 
506   // Callback invoked when an IPConfig restarts due to lease expiry.  This
507   // is advisory, since an "Updated" or "Failed" signal is guaranteed to
508   // follow.
509   void OnIPConfigExpired(const IPConfigRefPtr& ipconfig);
510 
511   // Called by Device so that subclasses can run hooks on the selected service
512   // failing to get an IP.  The default implementation disconnects the selected
513   // service with Service::kFailureDHCP.
514   virtual void OnIPConfigFailure();
515 
516   // Callback invoked on successful DHCPv6 configuration updates.
517   void OnDHCPv6ConfigUpdated(const IPConfigRefPtr& ipconfig,
518                              bool new_lease_acquired);
519 
520   // Callback invoked on DHCPv6 configuration failures.
521   void OnDHCPv6ConfigFailed(const IPConfigRefPtr& ipconfig);
522 
523   // Callback invoked when an DHCPv6Config restarts due to lease expiry.  This
524   // is advisory, since an "Updated" or "Failed" signal is guaranteed to
525   // follow.
526   void OnDHCPv6ConfigExpired(const IPConfigRefPtr& ipconfig);
527 
528   // Maintain connection state (Routes, IP Addresses and DNS) in the OS.
529   void CreateConnection();
530 
531   // Remove connection state
532   void DestroyConnection();
533 
534   // Selects a service to be "current" -- i.e. link-state or configuration
535   // events that happen to the device are attributed to this service.
536   void SelectService(const ServiceRefPtr& service);
537 
538   // Set the state of the |selected_service_|.
539   virtual void SetServiceState(Service::ConnectState state);
540 
541   // Set the failure of the selected service (implicitly sets the state to
542   // "failure").
543   virtual void SetServiceFailure(Service::ConnectFailure failure_state);
544 
545   // Records the failure mode and time of the selected service, and
546   // sets the Service state of the selected service to "Idle".
547   // Avoids showing a failure mole in the UI.
548   virtual void SetServiceFailureSilent(Service::ConnectFailure failure_state);
549 
550   // Called by the Portal Detector whenever a trial completes.  Device
551   // subclasses that choose unique mappings from portal results to connected
552   // states can override this method in order to do so.
553   virtual void PortalDetectorCallback(const PortalDetector::Result& result);
554 
555   // Initiate portal detection, if enabled for this device type.
556   bool StartPortalDetection();
557 
558   // Stop portal detection if it is running.
559   void StopPortalDetection();
560 
561   // Initiate connection diagnostics with the |result| from a completed portal
562   // detection attempt.
563   virtual bool StartConnectionDiagnosticsAfterPortalDetection(
564       const PortalDetector::Result& result);
565 
566   // Stop connection diagnostics if it is running.
567   void StopConnectionDiagnostics();
568 
569   // Stop connectivity tester if it exists.
570   void StopConnectivityTest();
571 
572   // Initiate link monitoring, if enabled for this device type.
573   bool StartLinkMonitor();
574 
575   // Stop link monitoring if it is running.
576   void StopLinkMonitor();
577 
578   // Respond to a LinkMonitor failure in a Device-specific manner.
579   virtual void OnLinkMonitorFailure();
580 
581   // Respond to a LinkMonitor gateway's MAC address found/change event.
582   virtual void OnLinkMonitorGatewayChange();
583 
584   // Returns true if traffic monitor is enabled on this device. The default
585   // implementation will return false, which can be overridden by a derived
586   // class.
587   virtual bool IsTrafficMonitorEnabled() const;
588 
589   // Initiates traffic monitoring on the device if traffic monitor is enabled.
590   void StartTrafficMonitor();
591 
592   // Stops traffic monitoring on the device if traffic monitor is enabled.
593   void StopTrafficMonitor();
594 
595   // Start DNS test for the given servers. When retry_until_success is set,
596   // callback will only be invoke when the test succeed or the test failed to
597   // start (internal error). This function will return false if there is a test
598   // that's already running, and true otherwise.
599   virtual bool StartDNSTest(
600       const std::vector<std::string>& dns_servers,
601       const bool retry_until_success,
602       const base::Callback<void(const DNSServerTester::Status)>& callback);
603   // Stop DNS test if one is running.
604   virtual void StopDNSTest();
605 
606   // Timer function for monitoring IPv6 DNS server's lifetime.
607   void StartIPv6DNSServerTimer(uint32_t lifetime_seconds);
608   void StopIPv6DNSServerTimer();
609 
610   // Stop all monitoring/testing activities on this device. Called when tearing
611   // down or changing network connection on the device.
612   void StopAllActivities();
613 
614   // Called by the Traffic Monitor when it detects a network problem. Device
615   // subclasses that want to roam to a different network when encountering
616   // network problems can override this method in order to do so. The parent
617   // implementation handles the metric reporting of the network problem.
618   virtual void OnEncounterNetworkProblem(int reason);
619 
620   // Set the state of the selected service, with checks to make sure
621   // the service is already in a connected state before doing so.
622   void SetServiceConnectedState(Service::ConnectState state);
623 
624   // Specifies whether an ARP gateway should be used for the
625   // device technology.
626   virtual bool ShouldUseArpGateway() const;
627 
628   // Indicates if the selected service is configured with a static IP address.
629   bool IsUsingStaticIP() const;
630 
631   // Indicates if the selected service is configured with static nameservers.
632   bool IsUsingStaticNameServers() const;
633 
selected_service()634   const ServiceRefPtr& selected_service() const { return selected_service_; }
635 
636   void HelpRegisterConstDerivedString(
637       const std::string& name,
638       std::string(Device::*get)(Error*));
639 
640   void HelpRegisterConstDerivedRpcIdentifier(
641       const std::string& name,
642       RpcIdentifier(Device::*get)(Error*));
643 
644   void HelpRegisterConstDerivedRpcIdentifiers(
645       const std::string& name,
646       RpcIdentifiers(Device::*get)(Error*));
647 
648   void HelpRegisterConstDerivedUint64(
649       const std::string& name,
650       uint64_t(Device::*get)(Error*));
651 
652   // Called by the ConnectionTester whenever a connectivity test completes.
653   virtual void ConnectionTesterCallback();
654 
655   // Property getters reserved for subclasses
control_interface()656   ControlInterface* control_interface() const { return control_interface_; }
metrics()657   Metrics* metrics() const { return metrics_; }
manager()658   Manager* manager() const { return manager_; }
link_monitor()659   const LinkMonitor* link_monitor() const { return link_monitor_.get(); }
660   void set_link_monitor(LinkMonitor* link_monitor);
661   // Use for unit test.
662   void set_traffic_monitor(TrafficMonitor* traffic_monitor);
663 
664   // Calculates the time (in seconds) till a DHCP lease is due for renewal,
665   // and stores this value in |result|. Returns false is there is no upcoming
666   // DHCP lease renewal, true otherwise.
667   bool TimeToNextDHCPLeaseRenewal(uint32_t* result);
668 
669  private:
670   friend class CellularCapabilityTest;
671   friend class CellularTest;
672   friend class DeviceAdaptorInterface;
673   friend class DeviceByteCountTest;
674   friend class DevicePortalDetectionTest;
675   friend class DeviceTest;
676   friend class EthernetTest;
677   friend class OpenVPNDriverTest;
678   friend class TestDevice;
679   friend class VirtualDeviceTest;
680   friend class WiFiObjectTest;
681 
682   static const char kIPFlagTemplate[];
683   static const char kIPFlagVersion4[];
684   static const char kIPFlagVersion6[];
685   static const char kIPFlagDisableIPv6[];
686   static const char kIPFlagUseTempAddr[];
687   static const char kIPFlagUseTempAddrUsedAndDefault[];
688   static const char kIPFlagReversePathFilter[];
689   static const char kIPFlagReversePathFilterEnabled[];
690   static const char kIPFlagReversePathFilterLooseMode[];
691   static const char kIPFlagArpAnnounce[];
692   static const char kIPFlagArpAnnounceDefault[];
693   static const char kIPFlagArpAnnounceBestLocal[];
694   static const char kIPFlagArpIgnore[];
695   static const char kIPFlagArpIgnoreDefault[];
696   static const char kIPFlagArpIgnoreLocalOnly[];
697   static const char kStoragePowered[];
698   static const char kStorageReceiveByteCount[];
699   static const char kStorageTransmitByteCount[];
700   static const char kFallbackDnsTestHostname[];
701   static const char* kFallbackDnsServers[];
702   static const int kDNSTimeoutMilliseconds;
703 
704   // Maximum seconds between two link monitor failures to declare this link
705   // (network) as unreliable.
706   static const int kLinkUnreliableThresholdSeconds;
707 
708   static const size_t kHardwareAddressLength;
709 
710   // Configure static IP address parameters if the service provides them.
711   void ConfigureStaticIPTask();
712 
713   // Right now, Devices reference IPConfigs directly when persisted to disk
714   // It's not clear that this makes sense long-term, but that's how it is now.
715   // This call generates a string in the right format for this persisting.
716   // |suffix| is injected into the storage identifier used for the configs.
717   std::string SerializeIPConfigs(const std::string& suffix);
718 
719   // Set an IP configuration flag on the device. |family| should be "ipv6" or
720   // "ipv4". |flag| should be the name of the flag to be set and |value| is
721   // what this flag should be set to. Overridden by unit tests to pretend
722   // writing to procfs.
723   virtual bool SetIPFlag(IPAddress::Family family,
724                          const std::string& flag,
725                          const std::string& value);
726 
727   // Request the removal of reverse-path filtering for this interface.
728   // This will allow packets destined for this interface to be accepted,
729   // even if this is not the default route for such a packet to arrive.
730   void DisableReversePathFilter();
731 
732   // Request reverse-path filtering for this interface.
733   void EnableReversePathFilter();
734 
735   // Disable ARP filtering on the device.  The interface will exhibit the
736   // default Linux behavior -- incoming ARP requests are responded to by all
737   // interfaces.  Outgoing ARP requests can contain any local address.
738   void DisableArpFiltering();
739 
740   // Enable ARP filtering on the device.  Incoming ARP requests are responded
741   // to only by the interface(s) owning the address.  Outgoing ARP requests
742   // will contain the best local address for the target.
743   void EnableArpFiltering();
744 
745   std::string GetSelectedServiceRpcIdentifier(Error* error);
746   std::vector<std::string> AvailableIPConfigs(Error* error);
747 
748   // Get the LinkMonitor's average response time.
749   uint64_t GetLinkMonitorResponseTime(Error* error);
750 
751   // Get receive and transmit byte counters. These methods simply wrap
752   // GetReceiveByteCount and GetTransmitByteCount in order to be used by
753   // HelpRegisterConstDerivedUint64.
754   uint64_t GetReceiveByteCountProperty(Error* error);
755   uint64_t GetTransmitByteCountProperty(Error* error);
756 
757   // Emit a property change signal for the "IPConfigs" property of this device.
758   void UpdateIPConfigsProperty();
759 
760   // Called by DNS server tester when the fallback DNS servers test completes.
761   void FallbackDNSResultCallback(const DNSServerTester::Status status);
762 
763   // Called by DNS server tester when the configured DNS servers test completes.
764   void ConfigDNSResultCallback(const DNSServerTester::Status status);
765 
766   // Update DNS setting with the given DNS servers for the current connection.
767   void SwitchDNSServers(const std::vector<std::string>& dns_servers);
768 
769   // Called when the lifetime for IPv6 DNS server expires.
770   void IPv6DNSServerExpired();
771 
772   // Return true if given IP configuration contain both IP address and DNS
773   // servers. Hence, ready to be used for network connection.
774   bool IPConfigCompleted(const IPConfigRefPtr& ipconfig);
775 
776   // Setup network connection with given IP configuration, and start portal
777   // detection on that connection.
778   void SetupConnection(const IPConfigRefPtr& ipconfig);
779 
780   // Set the system hostname to |hostname| if this device is configured to
781   // do so.  If |hostname| is too long, truncate this parameter to fit within
782   // the maximum hostname size.
783   bool SetHostname(const std::string& hostname);
784 
785   // Prepend the Manager's configured list of DNS servers into |ipconfig|
786   // ensuring that only DNS servers of the same address family as |ipconfig| are
787   // included in the final list.
788   void PrependDNSServersIntoIPConfig(const IPConfigRefPtr& ipconfig);
789 
790   // Mutate |servers| to include the Manager's prepended list of DNS servers for
791   // |family|.  On return, it is guaranteed that there are no duplicate entries
792   // in |servers|.
793   void PrependDNSServers(const IPAddress::Family family,
794                          std::vector<std::string>* servers);
795 
796   // Called by |connection_diagnostics| after diagnostics have finished.
797   void ConnectionDiagnosticsCallback(
798       const std::string& connection_issue,
799       const std::vector<ConnectionDiagnostics::Event>& diagnostic_events);
800 
801   // |enabled_persistent_| is the value of the Powered property, as
802   // read from the profile. If it is not found in the profile, it
803   // defaults to true. |enabled_| reflects the real-time state of
804   // the device, i.e., enabled or disabled. |enabled_pending_| reflects
805   // the target state of the device while an enable or disable operation
806   // is occurring.
807   //
808   // Some typical sequences for these state variables are shown below.
809   //
810   // Shill starts up, profile has been read:
811   //  |enabled_persistent_|=true   |enabled_|=false   |enabled_pending_|=false
812   //
813   // Shill acts on the value of |enabled_persistent_|, calls SetEnabled(true):
814   //  |enabled_persistent_|=true   |enabled_|=false   |enabled_pending_|=true
815   //
816   // SetEnabled completes successfully, device is enabled:
817   //  |enabled_persistent_|=true   |enabled_|=true    |enabled_pending_|=true
818   //
819   // User presses "Disable" button, SetEnabled(false) is called:
820   //  |enabled_persistent_|=false   |enabled_|=true    |enabled_pending_|=false
821   //
822   // SetEnabled completes successfully, device is disabled:
823   //  |enabled_persistent_|=false   |enabled_|=false    |enabled_pending_|=false
824   bool enabled_;
825   bool enabled_persistent_;
826   bool enabled_pending_;
827 
828   // Other properties
829   bool reconnect_;
830   const std::string hardware_address_;
831 
832   PropertyStore store_;
833 
834   const int interface_index_;
835   bool running_;  // indicates whether the device is actually in operation
836   const std::string link_name_;
837   const std::string unique_id_;
838   ControlInterface* control_interface_;
839   EventDispatcher* dispatcher_;
840   Metrics* metrics_;
841   Manager* manager_;
842   IPConfigRefPtr ipconfig_;
843   IPConfigRefPtr ip6config_;
844   IPConfigRefPtr dhcpv6_config_;
845   ConnectionRefPtr connection_;
846   base::WeakPtrFactory<Device> weak_ptr_factory_;
847   std::unique_ptr<DeviceAdaptorInterface> adaptor_;
848   std::unique_ptr<PortalDetector> portal_detector_;
849   std::unique_ptr<LinkMonitor> link_monitor_;
850   // Used for verifying whether DNS server is functional.
851   std::unique_ptr<DNSServerTester> dns_server_tester_;
852   base::Callback<void(const PortalDetector::Result&)>
853       portal_detector_callback_;
854   // Callback to invoke when IPv6 DNS servers lifetime expired.
855   base::CancelableClosure ipv6_dns_server_expired_callback_;
856   std::unique_ptr<TrafficMonitor> traffic_monitor_;
857   // DNS servers obtained from ipconfig (either from DHCP or static config)
858   // that are not working.
859   std::vector<std::string> config_dns_servers_;
860   Technology::Identifier technology_;
861   // The number of portal detection attempts from Connected to Online state.
862   // This includes all failure/timeout attempts and the final successful
863   // attempt.
864   int portal_attempts_to_online_;
865 
866   // Keep track of the offset between the interface-reported byte counters
867   // and our persisted value.
868   uint64_t receive_byte_offset_;
869   uint64_t transmit_byte_offset_;
870 
871   // Maintain a reference to the connected / connecting service
872   ServiceRefPtr selected_service_;
873 
874   // Cache singleton pointers for performance and test purposes.
875   DHCPProvider* dhcp_provider_;
876   RTNLHandler* rtnl_handler_;
877 
878   // Time when link monitor last failed.
879   Time* time_;
880   time_t last_link_monitor_failed_time_;
881   // Callback to invoke when link becomes reliable again after it was previously
882   // unreliable.
883   base::CancelableClosure reliable_link_callback_;
884 
885   std::unique_ptr<ConnectionTester> connection_tester_;
886   base::Callback<void()> connection_tester_callback_;
887 
888   // Track whether packets from non-optimal routes will be accepted by this
889   // device.  This is referred to as "loose mode" (see RFC3704).
890   bool is_loose_routing_;
891 
892   // Track the current same-net multi-home state.
893   bool is_multi_homed_;
894 
895   // Remember which flag files were previously successfully written.
896   std::set<std::string> written_flags_;
897 
898   std::unique_ptr<ConnectionDiagnostics> connection_diagnostics_;
899   base::Callback<void(const std::string&,
900                       const std::vector<ConnectionDiagnostics::Event>&)>
901       connection_diagnostics_callback_;
902 
903   DISALLOW_COPY_AND_ASSIGN(Device);
904 };
905 
906 }  // namespace shill
907 
908 #endif  // SHILL_DEVICE_H_
909