Home | History | Annotate | Download | only in shill
      1 //
      2 // Copyright (C) 2013 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_SERVICE_H_
     18 #define SHILL_SERVICE_H_
     19 
     20 #include <time.h>
     21 
     22 #include <map>
     23 #include <memory>
     24 #include <set>
     25 #include <string>
     26 #include <vector>
     27 
     28 #include <base/cancelable_callback.h>
     29 #include <base/memory/ref_counted.h>
     30 #include <base/memory/weak_ptr.h>
     31 #include <gtest/gtest_prod.h>  // for FRIEND_TEST
     32 
     33 #include "shill/accessor_interface.h"
     34 #include "shill/adaptor_interfaces.h"
     35 #include "shill/callbacks.h"
     36 #include "shill/dhcp_properties.h"
     37 #include "shill/net/event_history.h"
     38 #include "shill/net/shill_time.h"
     39 #include "shill/property_store.h"
     40 #include "shill/refptr_types.h"
     41 #include "shill/static_ip_parameters.h"
     42 #include "shill/technology.h"
     43 
     44 namespace chromeos_metrics {
     45 class Timer;
     46 }
     47 
     48 namespace shill {
     49 
     50 class ControlInterface;
     51 class DhcpProperties;
     52 class DiagnosticsReporter;
     53 class Endpoint;
     54 class Error;
     55 class EventDispatcher;
     56 class HTTPProxy;
     57 class KeyValueStore;
     58 class Manager;
     59 class Metrics;
     60 class MockManager;
     61 class ServiceAdaptorInterface;
     62 class ServiceMockAdaptor;
     63 class ServicePropertyChangeNotifier;
     64 class Sockets;
     65 class StoreInterface;
     66 
     67 #if !defined(DISABLE_WIFI) || !defined(DISABLE_WIRED_8021X)
     68 class EapCredentials;
     69 #endif  // DISABLE_WIFI || DISABLE_WIRED_8021X
     70 
     71 // A Service is a uniquely named entity, which the system can
     72 // connect in order to begin sending and receiving network traffic.
     73 // All Services are bound to an Entry, which represents the persistable
     74 // state of the Service.  If the Entry is populated at the time of Service
     75 // creation, that information is used to prime the Service.  If not, the Entry
     76 // becomes populated over time.
     77 class Service : public base::RefCounted<Service> {
     78  public:
     79   static const char kCheckPortalAuto[];
     80   static const char kCheckPortalFalse[];
     81   static const char kCheckPortalTrue[];
     82 
     83   static const char kErrorDetailsNone[];
     84 
     85   // TODO(pstew): Storage constants shouldn't need to be public
     86   // crbug.com/208736
     87   static const char kStorageAutoConnect[];
     88   static const char kStorageCheckPortal[];
     89   static const char kStorageDNSAutoFallback[];
     90   static const char kStorageError[];
     91   static const char kStorageFavorite[];
     92   static const char kStorageGUID[];
     93   static const char kStorageHasEverConnected[];
     94   static const char kStorageName[];
     95   static const char kStoragePriority[];
     96   static const char kStoragePriorityWithinTechnology[];
     97   static const char kStorageProxyConfig[];
     98   static const char kStorageSaveCredentials[];
     99   static const char kStorageType[];
    100   static const char kStorageUIData[];
    101   static const char kStorageConnectionId[];
    102   static const char kStorageLinkMonitorDisabled[];
    103   static const char kStorageManagedCredentials[];
    104 
    105   static const uint8_t kStrengthMax;
    106   static const uint8_t kStrengthMin;
    107 
    108   enum ConnectFailure {
    109     kFailureUnknown,
    110     kFailureAAA,
    111     kFailureActivation,
    112     kFailureBadPassphrase,
    113     kFailureBadWEPKey,
    114     kFailureConnect,
    115     kFailureDHCP,
    116     kFailureDNSLookup,
    117     kFailureEAPAuthentication,
    118     kFailureEAPLocalTLS,
    119     kFailureEAPRemoteTLS,
    120     kFailureHTTPGet,
    121     kFailureIPSecCertAuth,
    122     kFailureIPSecPSKAuth,
    123     kFailureInternal,
    124     kFailureNeedEVDO,
    125     kFailureNeedHomeNetwork,
    126     kFailureOTASP,
    127     kFailureOutOfRange,
    128     kFailurePPPAuth,
    129     kFailurePinMissing,
    130     kFailureMax
    131   };
    132   enum ConnectState {
    133     kStateUnknown,
    134     kStateIdle,
    135     kStateAssociating,
    136     kStateConfiguring,
    137     kStateConnected,
    138     kStatePortal,
    139     kStateFailure,
    140     kStateOnline
    141   };
    142   enum CryptoAlgorithm {
    143     kCryptoNone,
    144     kCryptoRc4,
    145     kCryptoAes
    146   };
    147 
    148   enum UpdateCredentialsReason{
    149     kReasonCredentialsLoaded,
    150     kReasonPropertyUpdate
    151   };
    152 
    153   static const int kPriorityNone;
    154 
    155   // A constructor for the Service object
    156   Service(ControlInterface* control_interface,
    157           EventDispatcher* dispatcher,
    158           Metrics* metrics,
    159           Manager* manager,
    160           Technology::Identifier technology);
    161 
    162   // AutoConnect MAY choose to ignore the connection request in some
    163   // cases. For example, if the corresponding Device only supports one
    164   // concurrent connection, and another Service is already connected
    165   // or connecting.
    166   //
    167   // AutoConnect MAY issue RPCs immediately. So AutoConnect MUST NOT
    168   // be called from a D-Bus signal handler context.
    169   virtual void AutoConnect();
    170   // Queue up a connection attempt. Derived classes SHOULD call the
    171   // base class implementation before beginning a connect. The base
    172   // class will log the connection attempt, and update base-class
    173   // state.
    174   virtual void Connect(Error* error, const char* reason);
    175   // Disconnect this service.  Override this method to add your service specific
    176   // disconnect logic, but call the super class's Disconnect() first.
    177   virtual void Disconnect(Error* error, const char* reason);
    178   // Disconnects this service via Disconnect().  Marks the service as having
    179   // failed with |failure|.  Do not override this method.
    180   virtual void DisconnectWithFailure(ConnectFailure failure,
    181                                      Error* error,
    182                                      const char* reason);
    183   // Disconnects this service via Disconnect(). The service will not be eligible
    184   // for auto-connect until a subsequent call to Connect, or Load.  Do not
    185   // override this method.
    186   virtual void UserInitiatedDisconnect(Error* error);
    187   // Connect to this service via Connect(). This function indicates that the
    188   // connection attempt is user-initiated.
    189   virtual void UserInitiatedConnect(Error* error);
    190 
    191   // The default implementation returns the error kInvalidArguments.
    192   virtual void ActivateCellularModem(const std::string& carrier,
    193                                      Error* error,
    194                                      const ResultCallback& callback);
    195   // The default implementation returns the error kNotSupported.
    196   virtual void CompleteCellularActivation(Error* error);
    197 
    198   virtual bool IsActive(Error* error);
    199 
    200   // Returns whether services of this type should be auto-connect by default.
    201   virtual bool IsAutoConnectByDefault() const { return false; }
    202 
    203   virtual ConnectState state() const { return state_; }
    204   // Updates the state of the Service and alerts the manager.  Also
    205   // clears |failure_| if the new state isn't a failure.
    206   virtual void SetState(ConnectState state);
    207   std::string GetStateString() const;
    208 
    209   // Set portal detection failure phase and status (reason). This function
    210   // is called when portal detection failed for the Service.
    211   virtual void SetPortalDetectionFailure(const std::string& phase,
    212                                          const std::string& status);
    213 
    214   // State utility functions
    215   static bool IsConnectedState(ConnectState state);
    216   static bool IsConnectingState(ConnectState state);
    217 
    218   virtual bool IsConnected() const;
    219   virtual bool IsConnecting() const;
    220   virtual bool IsFailed() const {
    221     // We sometimes lie about the failure state, to keep Chrome happy
    222     // (see comment in WiFi::HandleDisconnect). Hence, we check both
    223     // state and |failed_time_|.
    224     return state() == kStateFailure || failed_time_ > 0;
    225   }
    226 
    227   virtual bool IsInFailState() const {
    228     return state() == kStateFailure;
    229   }
    230 
    231   virtual bool IsOnline() const {
    232     return state() == kStateOnline;
    233   }
    234 
    235   // Returns true if the connection for |this| depends on service |b|.
    236   virtual bool IsDependentOn(const ServiceRefPtr& b) const;
    237 
    238   virtual bool IsPortalled() const {
    239     return state() == kStatePortal;
    240   }
    241 
    242   // Return true if service is allowed to automatically switch to fallback
    243   // DNS server.
    244   virtual bool is_dns_auto_fallback_allowed() const {
    245     return is_dns_auto_fallback_allowed_;
    246   }
    247 
    248   virtual bool link_monitor_disabled() const { return link_monitor_disabled_; }
    249 
    250   virtual ConnectFailure failure() const { return failure_; }
    251   // Sets the |previous_error_| property based on the current |failure_|, and
    252   // sets a serial number for this failure.
    253   virtual void SaveFailure();
    254   // Records the failure mode and time. Sets the Service state to "Failure".
    255   virtual void SetFailure(ConnectFailure failure);
    256   // Records the failure mode and time. Sets the Service state to "Idle".
    257   // Avoids showing a failure mole in the UI.
    258   virtual void SetFailureSilent(ConnectFailure failure);
    259 
    260   // Returns a string that is guaranteed to uniquely identify this Service
    261   // instance.
    262   const std::string& unique_name() const { return unique_name_; }
    263 
    264   virtual std::string GetRpcIdentifier() const;
    265 
    266   // Returns the unique persistent storage identifier for the service.
    267   virtual std::string GetStorageIdentifier() const = 0;
    268 
    269   // Returns the identifier within |storage| from which configuration for
    270   // this service can be loaded.  Returns an empty string if no entry in
    271   // |storage| can be used.
    272   virtual std::string GetLoadableStorageIdentifier(
    273       const StoreInterface& storage) const;
    274 
    275   // Returns whether the service configuration can be loaded from |storage|.
    276   virtual bool IsLoadableFrom(const StoreInterface& storage) const;
    277 
    278   // Returns true if the service uses 802.1x for key management.
    279   virtual bool Is8021x() const { return false; }
    280 
    281   // Loads the service from persistent |storage|. Returns true on success.
    282   virtual bool Load(StoreInterface* storage);
    283 
    284   // Indicate to service that it is no longer persisted to storage.  It
    285   // should purge any stored profile state (e.g., credentials).  Returns
    286   // true to indicate that this service should also be unregistered from
    287   // the manager, false otherwise.
    288   virtual bool Unload();
    289 
    290   // Attempt to remove the service. On failure, no changes in state will occur.
    291   virtual void Remove(Error* error);
    292 
    293   // Saves the service to persistent |storage|. Returns true on success.
    294   virtual bool Save(StoreInterface* storage);
    295 
    296   // Applies all the properties in |args| to this service object's mutable
    297   // store, except for those in parameters_ignored_for_configure_.
    298   // Returns an error in |error| if one or more parameter set attempts
    299   // fails, but will only return the first error.
    300   virtual void Configure(const KeyValueStore& args, Error* error);
    301 
    302   // Iterate over all the properties in |args| and test for an identical
    303   // value in this service object's store.  Returns false if one or more
    304   // keys in |args| do not exist or have different values, true otherwise.
    305   virtual bool DoPropertiesMatch(const KeyValueStore& args) const;
    306 
    307   // Returns whether portal detection is explicitly disabled on this service
    308   // via a property set on it.
    309   virtual bool IsPortalDetectionDisabled() const;
    310 
    311   // Returns whether portal detection is set to follow the default setting
    312   // of this service's technology via a property set on it.
    313   virtual bool IsPortalDetectionAuto() const;
    314 
    315   // Returns true if the service is persisted to a non-ephemeral profile.
    316   virtual bool IsRemembered() const;
    317 
    318   // Returns true if the service RPC identifier should be part of the
    319   // manager's advertised services list, false otherwise.
    320   virtual bool IsVisible() const { return true; }
    321 
    322   // Returns true if there is a proxy configuration set on this service.
    323   virtual bool HasProxyConfig() const { return !proxy_config_.empty(); }
    324 
    325   // Returns whether this service has had recent connection issues.
    326   virtual bool HasRecentConnectionIssues();
    327 
    328   // If the AutoConnect property has not already been marked as saved, set
    329   // its value to true and mark it saved.
    330   virtual void EnableAndRetainAutoConnect();
    331 
    332   // Set the connection for this service.  If the connection is non-NULL, create
    333   // an HTTP Proxy that will utilize this service's connection to serve
    334   // requests.
    335   virtual void SetConnection(const ConnectionRefPtr& connection);
    336   virtual const ConnectionRefPtr& connection() const { return connection_; }
    337 
    338   // Emit service's IP config change event to chrome.
    339   virtual void NotifyIPConfigChanges();
    340 
    341 #if !defined(DISABLE_WIFI) || !defined(DISABLE_WIRED_8021X)
    342   // Examines the EAP credentials for the service and returns true if a
    343   // connection attempt can be made.
    344   virtual bool Is8021xConnectable() const;
    345 
    346   // Add an EAP certification id |name| at position |depth| in the stack.
    347   // Returns true if entry was added, false otherwise.
    348   virtual bool AddEAPCertification(const std::string& name, size_t depth);
    349   // Clear all EAP certification elements.
    350   virtual void ClearEAPCertification();
    351 #endif  // DISABLE_WIFI || DISABLE_WIRED_8021X
    352 
    353   // Returns true if this service contains a IP address in its static IP
    354   // parameters, false otherwise.
    355   virtual bool HasStaticIPAddress() const;
    356 
    357   // Returns true if this service contains nameservers in its static IP
    358   // parameters, false otherwise.
    359   virtual bool HasStaticNameServers() const;
    360 
    361   // The inherited class that needs to send metrics after the service has
    362   // transitioned to the ready state should override this method.
    363   // |time_resume_to_ready_milliseconds| holds the elapsed time from when
    364   // the system was resumed until when the service transitioned to the
    365   // connected state.  This value is non-zero for the first service transition
    366   // to the connected state after a resume.
    367   virtual void SendPostReadyStateMetrics(
    368       int64_t /*time_resume_to_ready_milliseconds*/) const {}
    369 
    370   bool auto_connect() const { return auto_connect_; }
    371   void SetAutoConnect(bool connect);
    372 
    373   bool connectable() const { return connectable_; }
    374   // Sets the connectable property of the service, and broadcast the
    375   // new value. Does not update the manager.
    376   // TODO(petkov): Remove this method in favor of SetConnectableFull.
    377   void SetConnectable(bool connectable);
    378   // Sets the connectable property of the service, broadcasts the new
    379   // value, and alerts the manager if necessary.
    380   void SetConnectableFull(bool connectable);
    381 
    382   virtual bool explicitly_disconnected() const {
    383     return explicitly_disconnected_;
    384   }
    385 
    386   // Return RPC identifier for device that's internal to this service, which is
    387   // not registered with the manager.
    388   virtual std::string GetInnerDeviceRpcIdentifier() const { return ""; }
    389 
    390   bool retain_auto_connect() const { return retain_auto_connect_; }
    391   // Setter is deliberately omitted; use EnableAndRetainAutoConnect.
    392 
    393   void set_friendly_name(const std::string& n) { friendly_name_ = n; }
    394   const std::string& friendly_name() const { return friendly_name_; }
    395   // Sets the kNameProperty and broadcasts the change.
    396   void SetFriendlyName(const std::string& friendly_name);
    397 
    398   const std::string& guid() const { return guid_; }
    399   bool SetGuid(const std::string& guid, Error* error);
    400 
    401   bool has_ever_connected() const { return has_ever_connected_; }
    402   // Sets the has_ever_connected_ property of the service
    403   // and broadcasts the new value
    404   void SetHasEverConnected(bool has_ever_connected);
    405 
    406   int32_t priority() const { return priority_; }
    407   bool SetPriority(const int32_t& priority, Error* error);
    408   int32_t priority_within_technology() const {
    409       return priority_within_technology_;
    410   }
    411   bool SetPriorityWithinTechnology(const int32_t& priority, Error* error);
    412 
    413   size_t crypto_algorithm() const { return crypto_algorithm_; }
    414   bool key_rotation() const { return key_rotation_; }
    415   bool endpoint_auth() const { return endpoint_auth_; }
    416 
    417   void SetStrength(uint8_t strength);
    418 
    419   // uint8_t streams out as a char. Coerce to a larger type, so that
    420   // it prints as a number.
    421   uint16_t strength() const { return strength_; }
    422 
    423   virtual Technology::Identifier technology() const { return technology_; }
    424   std::string GetTechnologyString() const;
    425 
    426 #if !defined(DISABLE_WIFI) || !defined(DISABLE_WIRED_8021X)
    427   virtual const EapCredentials* eap() const { return eap_.get(); }
    428   void SetEapCredentials(EapCredentials* eap);
    429 #endif  // DISABLE_WIFI || DISABLE_WIRED_8021X
    430 
    431   bool save_credentials() const { return save_credentials_; }
    432   void set_save_credentials(bool save) { save_credentials_ = save; }
    433 
    434   const std::string& error() const { return error_; }
    435   void set_error(const std::string& error) { error_ = error; }
    436 
    437   const std::string& error_details() const { return error_details_; }
    438   void SetErrorDetails(const std::string& details);
    439 
    440   static const char* ConnectFailureToString(const ConnectFailure& state);
    441   static const char* ConnectStateToString(const ConnectState& state);
    442 
    443   // Compare two services.  Returns true if Service |a| should be displayed
    444   // above |b|.  If |compare_connectivity_state| is true, the connectivity
    445   // state of the service (service->state()) is used as the most significant
    446   // criteria for comparsion, otherwise the service state is ignored.  Use
    447   // |tech_order| to rank services if more decisive criteria do not yield a
    448   // difference.  |reason| is populated with the exact criteria used for the
    449   // ultimate comparison.
    450   static bool Compare(Manager* manager,
    451                       ServiceRefPtr a,
    452                       ServiceRefPtr b,
    453                       bool compare_connectivity_state,
    454                       const std::vector<Technology::Identifier>& tech_order,
    455                       const char** reason);
    456 
    457   // These are defined in service.cc so that we don't have to include profile.h
    458   // TODO(cmasone): right now, these are here only so that we can get the
    459   // profile name as a property.  Can we store just the name, and then handle
    460   // setting the profile for this service via |manager_|?
    461   const ProfileRefPtr& profile() const;
    462 
    463   // Sets the profile property of this service. Broadcasts the new value if it's
    464   // not nullptr. If the new value is nullptr, the service will either be set to
    465   // another profile afterwards or it will not be visible and not monitored
    466   // anymore.
    467   void SetProfile(const ProfileRefPtr& p);
    468 
    469   // This is called from tests and shouldn't be called otherwise. Use SetProfile
    470   // instead.
    471   void set_profile(const ProfileRefPtr& p);
    472 
    473   // Notification that occurs when a service now has profile data saved
    474   // on its behalf.  Some service types like WiFi can choose to register
    475   // themselves at this point.
    476   virtual void OnProfileConfigured() {}
    477 
    478   // Notification that occurs when a single property has been changed via
    479   // the RPC adaptor.
    480   virtual void OnPropertyChanged(const std::string& property);
    481 
    482   // Notification that occurs when an EAP credential property has been
    483   // changed.  Some service subclasses can choose to respond to this
    484   // event.
    485   virtual void OnEapCredentialsChanged(UpdateCredentialsReason reason) {}
    486 
    487   // Called by the manager once after a resume.
    488   virtual void OnAfterResume();
    489 
    490   // Called by the manager once when entering dark resume.
    491   virtual void OnDarkResume();
    492 
    493   // Called by the manager to clear remembered state of being explicitly
    494   // disconnected.
    495   virtual void ClearExplicitlyDisconnected();
    496 
    497 #if !defined(DISABLE_WIFI) || !defined(DISABLE_WIRED_8021X)
    498   EapCredentials* mutable_eap() { return eap_.get(); }
    499 #endif  // DISABLE_WIFI || DISABLE_WIRED_8021X
    500 
    501   const DhcpProperties& dhcp_properties() const {
    502     return *dhcp_properties_;
    503   }
    504 
    505   PropertyStore* mutable_store() { return &store_; }
    506   const PropertyStore& store() const { return store_; }
    507   StaticIPParameters* mutable_static_ip_parameters() {
    508     return &static_ip_parameters_;
    509   }
    510   const StaticIPParameters& static_ip_parameters() const {
    511     return static_ip_parameters_;
    512   }
    513 
    514   // Retrieves |key| from |id| in |storage| to |value|.  If this key does
    515   // not exist, assign |default_value| to |value|.
    516   static void LoadString(StoreInterface* storage,
    517                          const std::string& id,
    518                          const std::string& key,
    519                          const std::string& default_value,
    520                          std::string* value);
    521 
    522   // Assigns |value| to |key| in |storage| if |value| is non-empty and |save| is
    523   // true. Otherwise, removes |key| from |storage|. If |crypted| is true, the
    524   // value is encrypted.
    525   static void SaveString(StoreInterface* storage,
    526                          const std::string& id,
    527                          const std::string& key,
    528                          const std::string& value,
    529                          bool crypted,
    530                          bool save);
    531 
    532   // Called via RPC to get a dict containing profile-to-entry_name mappings
    533   // of all the profile entires which contain configuration applicable to
    534   // this service.
    535   std::map<std::string, std::string> GetLoadableProfileEntries();
    536 
    537   void set_connection_id(int connection_id) { connection_id_ = connection_id; }
    538   int connection_id() const { return connection_id_; }
    539 
    540   void set_unreliable(bool unreliable) { unreliable_ = unreliable; }
    541   bool unreliable() const { return unreliable_; }
    542 
    543  protected:
    544   friend class base::RefCounted<Service>;
    545 
    546   static const char kAutoConnBusy[];
    547 
    548   virtual ~Service();
    549 
    550   // Returns true if a character is allowed to be in a service storage id.
    551   static bool LegalChar(char a) { return isalnum(a) || a == '_'; }
    552 
    553   // Returns true if a character is disallowed to be in a service storage id.
    554   static bool IllegalChar(char a) { return !LegalChar(a); }
    555 
    556   virtual std::string CalculateState(Error* error);
    557   std::string CalculateTechnology(Error* error);
    558 
    559   bool GetVisibleProperty(Error* error);
    560 
    561   // Returns whether this service is in a state conducive to auto-connect.
    562   // This should include any tests used for computing connectable(),
    563   // as well as other critera such as whether the device associated with
    564   // this service is busy with another connection.
    565   //
    566   // If the service is not auto-connectable, |*reason| will be set to
    567   // point to C-string explaining why the service is not auto-connectable.
    568   virtual bool IsAutoConnectable(const char** reason) const;
    569 
    570   // HelpRegisterDerived*: Expose a property over RPC, with the name |name|.
    571   //
    572   // Reads of the property will be handled by invoking |get|.
    573   // Writes to the property will be handled by invoking |set|.
    574   // Clearing the property will be handled by PropertyStore.
    575   void HelpRegisterDerivedBool(
    576       const std::string& name,
    577       bool(Service::*get)(Error* error),
    578       bool(Service::*set)(const bool& value, Error* error),
    579       void(Service::*clear)(Error* error));
    580   void HelpRegisterDerivedInt32(
    581       const std::string& name,
    582       int32_t(Service::*get)(Error* error),
    583       bool(Service::*set)(const int32_t& value, Error* error));
    584   void HelpRegisterDerivedString(
    585       const std::string& name,
    586       std::string(Service::*get)(Error* error),
    587       bool(Service::*set)(const std::string& value, Error* error));
    588   void HelpRegisterConstDerivedUint16(
    589       const std::string& name,
    590       uint16_t(Service::*get)(Error* error) const);
    591   void HelpRegisterConstDerivedRpcIdentifier(
    592       const std::string& name,
    593       std::string(Service::*get)(Error*) const);
    594   void HelpRegisterConstDerivedStrings(
    595       const std::string& name, Strings(Service::*get)(Error* error) const);
    596   void HelpRegisterConstDerivedString(
    597       const std::string& name, std::string(Service::*get)(Error* error) const);
    598 
    599   // HelpRegisterObservedDerived*: Expose an property over RPC, with the
    600   // name |name|, for which property changes are automatically generated.
    601   //
    602   void HelpRegisterObservedDerivedBool(
    603       const std::string& name,
    604       bool(Service::*get)(Error* error),
    605       bool(Service::*set)(const bool& value, Error* error),
    606       void(Service::*clear)(Error* error));
    607   ServiceAdaptorInterface* adaptor() const { return adaptor_.get(); }
    608 
    609 #if !defined(DISABLE_WIFI) || !defined(DISABLE_WIRED_8021X)
    610   void UnloadEapCredentials();
    611 #endif  // DISABLE_WIFI || DISABLE_WIRED_8021X
    612 
    613   // Ignore |parameter| when performing a Configure() operation.
    614   void IgnoreParameterForConfigure(const std::string& parameter);
    615 
    616   // Update the service's string-based "Error" RPC property based on the
    617   // failure_ enum.
    618   void UpdateErrorProperty();
    619 
    620   // RPC setter for the the "AutoConnect" property. Updates the |manager_|.
    621   // (cf. SetAutoConnect, which does not update the manager.)
    622   virtual bool SetAutoConnectFull(const bool& connect, Error* error);
    623 
    624   // RPC clear method for the "AutoConnect" property.  Sets the AutoConnect
    625   // property back to its default value, and clears the retain_auto_connect_
    626   // property to allow the AutoConnect property to be enabled automatically.
    627   void ClearAutoConnect(Error* error);
    628 
    629   // Property accessors reserved for subclasses
    630   EventDispatcher* dispatcher() const { return dispatcher_; }
    631   ControlInterface* control_interface() const { return control_interface_; }
    632 #if !defined(DISABLE_WIFI) || !defined(DISABLE_WIRED_8021X)
    633   const std::string& GetEAPKeyManagement() const;
    634   virtual void SetEAPKeyManagement(const std::string& key_management);
    635 #endif  // DISABLE_WIFI || DISABLE_WIRED_8021X
    636 
    637   Manager* manager() const { return manager_; }
    638   Metrics* metrics() const { return metrics_; }
    639 
    640   // Save the serivce's auto_connect value, without affecting its auto_connect
    641   // property itself. (cf. EnableAndRetainAutoConnect)
    642   void RetainAutoConnect();
    643 
    644   // Inform base class of the security properties for the service.
    645   //
    646   // NB: When adding a call to this function from a subclass, please check
    647   // that the semantics of SecurityLevel() are appropriate for the subclass.
    648   void SetSecurity(CryptoAlgorithm crypt, bool rotation, bool endpoint_auth);
    649 
    650   // Return whether this service is suspected or confirmed to be
    651   // provided by a mobile device, which is likely to be using a
    652   // metered backhaul for internet connectivity.
    653   virtual std::string GetTethering(Error* error) const;
    654 
    655   // Emit property change notifications for all observed properties.
    656   void NotifyPropertyChanges();
    657 
    658  private:
    659   friend class ActivePassiveOutOfCreditsDetectorTest;
    660   friend class EthernetEapServiceTest;
    661   friend class EthernetServiceTest;
    662   friend class MetricsTest;
    663   friend class ManagerTest;
    664   friend class ServiceAdaptorInterface;
    665   friend class ServiceTest;
    666   friend class SubscriptionStateOutOfCreditsDetectorTest;
    667   friend class VPNProviderTest;
    668   friend class VPNServiceTest;
    669   friend class WiFiServiceTest;
    670   friend class WiMaxProviderTest;
    671   friend class WiMaxServiceTest;
    672   friend void TestCommonPropertyChanges(ServiceRefPtr, ServiceMockAdaptor*);
    673   friend void TestCustomSetterNoopChange(ServiceRefPtr, MockManager*);
    674   friend void TestNamePropertyChange(ServiceRefPtr, ServiceMockAdaptor*);
    675   FRIEND_TEST(AllMockServiceTest, AutoConnectWithFailures);
    676   FRIEND_TEST(CellularCapabilityGSMTest, SetStorageIdentifier);
    677   FRIEND_TEST(CellularServiceTest, IsAutoConnectable);
    678   FRIEND_TEST(DeviceTest, AcquireIPConfigWithoutSelectedService);
    679   FRIEND_TEST(DeviceTest, AcquireIPConfigWithSelectedService);
    680   FRIEND_TEST(DeviceTest, IPConfigUpdatedFailureWithStatic);
    681   FRIEND_TEST(ManagerTest, ConnectToBestServices);
    682   FRIEND_TEST(ServiceTest, AutoConnectLogging);
    683   FRIEND_TEST(ServiceTest, CalculateState);
    684   FRIEND_TEST(ServiceTest, CalculateTechnology);
    685   FRIEND_TEST(ServiceTest, Certification);
    686   FRIEND_TEST(ServiceTest, Compare);
    687   FRIEND_TEST(ServiceTest, ConfigureEapStringProperty);
    688   FRIEND_TEST(ServiceTest, ConfigureIgnoredProperty);
    689   FRIEND_TEST(ServiceTest, Constructor);
    690   FRIEND_TEST(ServiceTest, CustomSetterNoopChange);
    691   FRIEND_TEST(ServiceTest, GetIPConfigRpcIdentifier);
    692   FRIEND_TEST(ServiceTest, GetProperties);
    693   FRIEND_TEST(ServiceTest, GetTethering);
    694   FRIEND_TEST(ServiceTest, IsAutoConnectable);
    695   FRIEND_TEST(ServiceTest, IsDependentOn);
    696   FRIEND_TEST(ServiceTest, Load);
    697   FRIEND_TEST(ServiceTest, LoadAutoConnect);
    698   FRIEND_TEST(ServiceTest, PortalDetectionFailure);
    699   FRIEND_TEST(ServiceTest, RecheckPortal);
    700   FRIEND_TEST(ServiceTest, Save);
    701   FRIEND_TEST(ServiceTest, SaveString);
    702   FRIEND_TEST(ServiceTest, SaveStringCrypted);
    703   FRIEND_TEST(ServiceTest, SaveStringDontSave);
    704   FRIEND_TEST(ServiceTest, SaveStringEmpty);
    705   FRIEND_TEST(ServiceTest, SecurityLevel);
    706   FRIEND_TEST(ServiceTest, SetCheckPortal);
    707   FRIEND_TEST(ServiceTest, SetConnectableFull);
    708   FRIEND_TEST(ServiceTest, SetFriendlyName);
    709   FRIEND_TEST(ServiceTest, SetProperty);
    710   FRIEND_TEST(ServiceTest, State);
    711   FRIEND_TEST(ServiceTest, StateResetAfterFailure);
    712   FRIEND_TEST(ServiceTest, UniqueAttributes);
    713   FRIEND_TEST(ServiceTest, Unload);
    714   FRIEND_TEST(ServiceTest, UserInitiatedConnectionResult);
    715   FRIEND_TEST(WiFiServiceTest, SetPassphraseResetHasEverConnected);
    716   FRIEND_TEST(WiFiServiceTest, SuspectedCredentialFailure);
    717   FRIEND_TEST(WiFiServiceTest, SetPassphraseRemovesCachedCredentials);
    718   FRIEND_TEST(WiFiServiceTest, LoadPassphraseClearCredentials);
    719   FRIEND_TEST(WiFiTimerTest, ReconnectTimer);
    720   FRIEND_TEST(WiFiMainTest, EAPEvent);  // For eap_.
    721   FRIEND_TEST(WiMaxServiceTest, ChangeCredResetHasEverConnected);
    722   FRIEND_TEST(EthernetEapServiceTest, OnEapCredentialsChanged);
    723 
    724   static const char kAutoConnConnected[];
    725   static const char kAutoConnConnecting[];
    726   static const char kAutoConnExplicitDisconnect[];
    727   static const char kAutoConnNotConnectable[];
    728   static const char kAutoConnOffline[];
    729   static const char kAutoConnTechnologyNotConnectable[];
    730   static const char kAutoConnThrottled[];
    731 
    732 #if !defined(DISABLE_WIFI) || !defined(DISABLE_WIRED_8021X)
    733   static const size_t kEAPMaxCertificationElements;
    734 #endif  // DISABLE_WIFI || DISABLE_WIRED_8021X
    735 
    736   static const char kServiceSortAutoConnect[];
    737   static const char kServiceSortConnectable[];
    738   static const char kServiceSortHasEverConnected[];
    739   static const char kServiceSortIsConnected[];
    740   static const char kServiceSortDependency[];
    741   static const char kServiceSortIsConnecting[];
    742   static const char kServiceSortIsFailed[];
    743   static const char kServiceSortIsOnline[];
    744   static const char kServiceSortIsPortalled[];
    745   static const char kServiceSortPriority[];
    746   static const char kServiceSortPriorityWithinTechnology[];
    747   static const char kServiceSortSecurity[];
    748   static const char kServiceSortProfileOrder[];
    749   static const char kServiceSortEtc[];
    750   static const char kServiceSortSerialNumber[];
    751   static const char kServiceSortTechnology[];
    752 
    753   static const uint64_t kMaxAutoConnectCooldownTimeMilliseconds;
    754   static const uint64_t kMinAutoConnectCooldownTimeMilliseconds;
    755   static const uint64_t kAutoConnectCooldownBackoffFactor;
    756 
    757   static const int kDisconnectsMonitorSeconds;
    758   static const int kMisconnectsMonitorSeconds;
    759   static const int kReportDisconnectsThreshold;
    760   static const int kReportMisconnectsThreshold;
    761   static const int kMaxDisconnectEventHistory;
    762   static const int kMaxMisconnectEventHistory;
    763 
    764   bool GetAutoConnect(Error* error);
    765 
    766   std::string GetCheckPortal(Error* error);
    767   bool SetCheckPortal(const std::string& check_portal, Error* error);
    768 
    769   std::string GetGuid(Error* error);
    770 
    771   virtual std::string GetDeviceRpcId(Error* error) const = 0;
    772 
    773   std::string GetIPConfigRpcIdentifier(Error* error) const;
    774 
    775   std::string GetNameProperty(Error* error);
    776   // The base implementation asserts that |name| matches the current Name
    777   // property value.
    778   virtual bool SetNameProperty(const std::string& name, Error* error);
    779 
    780   int32_t GetPriority(Error* error);
    781   int32_t GetPriorityWithinTechnology(Error* error);
    782 
    783   std::string GetProfileRpcId(Error* error);
    784   bool SetProfileRpcId(const std::string& profile, Error* error);
    785 
    786   // Returns TCP port of service's HTTP proxy in host order.
    787   uint16_t GetHTTPProxyPort(Error* error) const;
    788 
    789   std::string GetProxyConfig(Error* error);
    790   bool SetProxyConfig(const std::string& proxy_config, Error* error);
    791 
    792   Strings GetDisconnectsProperty(Error* error) const;
    793   Strings GetMisconnectsProperty(Error* error) const;
    794 
    795   void ReEnableAutoConnectTask();
    796   // Disables autoconnect and posts a task to re-enable it after a cooldown.
    797   // Note that autoconnect could be disabled for other reasons as well.
    798   void ThrottleFutureAutoConnects();
    799 
    800   // Saves settings to profile, if we have one. Unlike
    801   // SaveServiceToProfile, SaveToProfile never assigns this service
    802   // into a profile.
    803   void SaveToProfile();
    804 
    805   // Qualify the conditions under which the most recent disconnect occurred.
    806   // Make note ot the fact that there was a problem connecting / staying
    807   // connected if the disconnection did not occur as a clear result of user
    808   // action.
    809   void NoteDisconnectEvent();
    810 
    811   // Utility function that returns true if a is different from b.  When they
    812   // are, "decision" is populated with the boolean value of "a > b".
    813   static bool DecideBetween(int a, int b, bool* decision);
    814 
    815   // Report the result of user-initiated connection attempt to UMA stats.
    816   // Currently only report stats for wifi service.
    817   void ReportUserInitiatedConnectionResult(ConnectState state);
    818 
    819   // Linearize security parameters (crypto algorithm, key rotation, endpoint
    820   // authentication) for comparison.
    821   uint16_t SecurityLevel();
    822 
    823   // WeakPtrFactory comes first, so that other fields can use it.
    824   base::WeakPtrFactory<Service> weak_ptr_factory_;
    825 
    826   ConnectState state_;
    827   ConnectState previous_state_;
    828   ConnectFailure failure_;
    829   bool auto_connect_;
    830 
    831   // Denotes whether the value of auto_connect_ property value should be
    832   // retained, i.e. only be allowed to change via explicit property changes
    833   // from the UI.
    834   bool retain_auto_connect_;
    835 
    836   std::string check_portal_;
    837   bool connectable_;
    838   std::string error_;
    839   std::string error_details_;
    840   std::string previous_error_;
    841   int32_t previous_error_serial_number_;
    842   bool explicitly_disconnected_;
    843   bool is_in_user_connect_;
    844   int32_t priority_;
    845   int32_t priority_within_technology_;
    846   uint8_t crypto_algorithm_;
    847   bool key_rotation_;
    848   bool endpoint_auth_;
    849   std::string portal_detection_failure_phase_;
    850   std::string portal_detection_failure_status_;
    851 
    852   uint8_t strength_;
    853   std::string proxy_config_;
    854   std::string ui_data_;
    855   std::string guid_;
    856   bool save_credentials_;
    857 #if !defined(DISABLE_WIFI) || !defined(DISABLE_WIRED_8021X)
    858   std::unique_ptr<EapCredentials> eap_;
    859 #endif  // DISABLE_WIFI || DISABLE_WIRED_8021X
    860   std::unique_ptr<DhcpProperties> dhcp_properties_;
    861   Technology::Identifier technology_;
    862   // The time of the most recent failure. Value is 0 if the service is
    863   // not currently failed.
    864   time_t failed_time_;
    865   // Whether or not this service has ever reached kStateConnected.
    866   bool has_ever_connected_;
    867 
    868   EventHistory disconnects_;  // Connection drops.
    869   EventHistory misconnects_;  // Failures to connect.
    870 
    871   base::CancelableClosure reenable_auto_connect_task_;
    872   uint64_t auto_connect_cooldown_milliseconds_;
    873 
    874   ProfileRefPtr profile_;
    875   PropertyStore store_;
    876   std::set<std::string> parameters_ignored_for_configure_;
    877 
    878   EventDispatcher* dispatcher_;
    879   ControlInterface* control_interface_;
    880   unsigned int serial_number_;
    881   std::string unique_name_;  // MUST be unique amongst service instances
    882 
    883   // Service's friendly name is presented through the UI. By default it's the
    884   // same as |unique_name_| but normally Service subclasses override
    885   // it. WARNING: Don't log the friendly name at the default logging level due
    886   // to PII concerns.
    887   std::string friendly_name_;
    888 
    889   // List of subject names reported by remote entity during TLS setup.
    890   std::vector<std::string> remote_certification_;
    891 
    892   std::unique_ptr<ServiceAdaptorInterface> adaptor_;
    893   std::unique_ptr<ServicePropertyChangeNotifier> property_change_notifier_;
    894   std::unique_ptr<HTTPProxy> http_proxy_;
    895   ConnectionRefPtr connection_;
    896   StaticIPParameters static_ip_parameters_;
    897   Metrics* metrics_;
    898   Manager* manager_;
    899   std::unique_ptr<Sockets> sockets_;
    900   Time* time_;
    901   DiagnosticsReporter* diagnostics_reporter_;
    902 
    903   // The |serial_number_| for the next Service.
    904   static unsigned int next_serial_number_;
    905 
    906   // Network identifier indicating the network (gateway) the service is
    907   // connected to.
    908   int connection_id_;
    909   // When set to true, this service will automatically fallback to Google's DNS
    910   // servers if the portal detection failed due to DNS failure and Google's DNS
    911   // servers are working.
    912   bool is_dns_auto_fallback_allowed_;
    913   // When set to true, will not start link monitor when the connection to this
    914   // service is established.
    915   bool link_monitor_disabled_;
    916   // When set to true, the credentials for this service will be considered
    917   // valid, and will not require an initial connection to rank it highly for
    918   // auto-connect.
    919   bool managed_credentials_;
    920   // Flag indicating if this service is unreliable (experiencing multiple
    921   // link monitor failures in a short period of time).
    922   bool unreliable_;
    923 
    924   DISALLOW_COPY_AND_ASSIGN(Service);
    925 };
    926 
    927 }  // namespace shill
    928 
    929 #endif  // SHILL_SERVICE_H_
    930