mobile_activator.h revision 5d1f7b1de12d16ceb2c938c56701a3e8bfa558f7
1// Copyright (c) 2012 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#ifndef CHROME_BROWSER_CHROMEOS_MOBILE_MOBILE_ACTIVATOR_H_
6#define CHROME_BROWSER_CHROMEOS_MOBILE_MOBILE_ACTIVATOR_H_
7
8#include <map>
9#include <string>
10
11#include "base/files/file_path.h"
12#include "base/gtest_prod_util.h"
13#include "base/memory/scoped_ptr.h"
14#include "base/memory/singleton.h"
15#include "base/memory/weak_ptr.h"
16#include "base/observer_list.h"
17#include "base/timer/timer.h"
18#include "chromeos/network/network_handler_callbacks.h"
19#include "chromeos/network/network_state_handler_observer.h"
20
21namespace base {
22class DictionaryValue;
23}
24
25namespace chromeos {
26
27class NetworkState;
28class TestMobileActivator;
29
30// Cellular plan config document.
31class CellularConfigDocument
32    : public base::RefCountedThreadSafe<CellularConfigDocument> {
33 public:
34  CellularConfigDocument();
35
36  // Return error message for a given code.
37  std::string GetErrorMessage(const std::string& code);
38  void LoadCellularConfigFile();
39  const std::string& version() { return version_; }
40
41 private:
42  friend class base::RefCountedThreadSafe<CellularConfigDocument>;
43  typedef std::map<std::string, std::string> ErrorMap;
44
45  virtual ~CellularConfigDocument();
46
47  void SetErrorMap(const ErrorMap& map);
48  bool LoadFromFile(const base::FilePath& config_path);
49
50  std::string version_;
51  ErrorMap error_map_;
52  base::Lock config_lock_;
53
54  DISALLOW_COPY_AND_ASSIGN(CellularConfigDocument);
55};
56
57// This class performs mobile plan activation process.
58class MobileActivator
59    : public base::SupportsWeakPtr<MobileActivator>,
60      public NetworkStateHandlerObserver {
61 public:
62  // Activation state.
63  enum PlanActivationState {
64    // Activation WebUI page is loading, activation not started.
65    PLAN_ACTIVATION_PAGE_LOADING            = -1,
66    // Activation process started.
67    PLAN_ACTIVATION_START                   = 0,
68    // Initial over the air activation attempt.
69    PLAN_ACTIVATION_TRYING_OTASP            = 1,
70    // Performing pre-activation process.
71    PLAN_ACTIVATION_INITIATING_ACTIVATION   = 3,
72    // Reconnecting to network. Used for networks activated over cellular
73    // connection.
74    PLAN_ACTIVATION_RECONNECTING            = 4,
75    // Passively waiting for a network connection. Used for networks activated
76    // over non-cellular network.
77    PLAN_ACTIVATION_WAITING_FOR_CONNECTION  = 5,
78    // Loading payment portal page.
79    PLAN_ACTIVATION_PAYMENT_PORTAL_LOADING  = 6,
80    // Showing payment portal page.
81    PLAN_ACTIVATION_SHOWING_PAYMENT         = 7,
82    // Decides whether to load the portal again or call us done.
83    PLAN_ACTIVATION_RECONNECTING_PAYMENT    = 8,
84    // Delaying activation until payment portal catches up.
85    PLAN_ACTIVATION_DELAY_OTASP             = 9,
86    // Starting post-payment activation attempt.
87    PLAN_ACTIVATION_START_OTASP             = 10,
88    // Attempting activation.
89    PLAN_ACTIVATION_OTASP                   = 11,
90    // Finished activation.
91    PLAN_ACTIVATION_DONE                    = 12,
92    // Error occured during activation process.
93    PLAN_ACTIVATION_ERROR                   = 0xFF,
94  };
95
96  // Activation process observer.
97  class Observer {
98   public:
99    // Signals activation |state| change for given |network|.
100    virtual void OnActivationStateChanged(
101        const NetworkState* network,
102        PlanActivationState state,
103        const std::string& error_description) = 0;
104
105   protected:
106    Observer() {}
107    virtual ~Observer() {}
108  };
109
110  static MobileActivator* GetInstance();
111
112  // Add/remove activation process observer.
113  void AddObserver(Observer* observer);
114  void RemoveObserver(Observer* observer);
115
116  // Activation is in process.
117  bool RunningActivation() const;
118  // Activation state.
119  PlanActivationState state() const { return state_; }
120  // Initiates activation process.  Can only be called from the UI thread.
121  void InitiateActivation(const std::string& service_path);
122  // Terminates activation process if already started.
123  void TerminateActivation();
124  // Process portal load attempt status.
125  void OnPortalLoaded(bool success);
126  // Process payment transaction status.
127  void OnSetTransactionStatus(bool success);
128
129 private:
130  friend struct DefaultSingletonTraits<MobileActivator>;
131  friend class TestMobileActivator;
132  FRIEND_TEST_ALL_PREFIXES(MobileActivatorTest, BasicFlowForNewDevices);
133  FRIEND_TEST_ALL_PREFIXES(MobileActivatorTest, OTASPScheduling);
134  FRIEND_TEST_ALL_PREFIXES(MobileActivatorTest,
135                           ReconnectOnDisconnectFromPaymentPortal);
136  FRIEND_TEST_ALL_PREFIXES(MobileActivatorTest, StartAtStart);
137  // We reach directly into the activator for testing purposes.
138  friend class MobileActivatorTest;
139
140  MobileActivator();
141  virtual ~MobileActivator();
142
143  // NetworkStateHandlerObserver overrides.
144  virtual void DefaultNetworkChanged(const NetworkState* network) OVERRIDE;
145  virtual void NetworkPropertiesUpdated(const NetworkState* network) OVERRIDE;
146
147  // Continue activation after inital setup (config load). Makes an
148  // asynchronous call to NetworkConfigurationHandler::GetProperties.
149  void ContinueActivation();
150  void GetPropertiesAndContinueActivation(
151      const std::string& service_path,
152      const base::DictionaryValue& properties);
153  void GetPropertiesFailure(const std::string& error_name,
154                            scoped_ptr<base::DictionaryValue> error_data);
155  // Handles the signal that the payment portal has finished loading.
156  void HandlePortalLoaded(bool success);
157  // Handles the signal that the user has finished with the portal.
158  void HandleSetTransactionStatus(bool success);
159  // Starts activation.
160  void StartActivation();
161  // Called after we delay our OTASP (after payment).
162  void RetryOTASP();
163  // Continues activation process. This method is called after we disconnect
164  // due to detected connectivity issue to kick off reconnection.
165  void ContinueConnecting();
166
167  // Sends message to host registration page with system/user info data.
168  void SendDeviceInfo();
169
170  // Starts OTASP process.
171  void StartOTASP();
172  // Called when an OTASP attempt times out.
173  void HandleOTASPTimeout();
174  // Forces disconnect / reconnect when we detect portal connectivity issues.
175  void ForceReconnect(const NetworkState* network,
176                      PlanActivationState next_state);
177  // Called when ForceReconnect takes too long to reconnect.
178  void ReconnectTimedOut();
179
180  // Called on default network changes to update cellular network activation
181  // state.
182  void RefreshCellularNetworks();
183
184  // Helper to get network state corresponding to service path. Provided
185  // for easy mocking in unit tests.
186  virtual const NetworkState* GetNetworkState(const std::string& service_path);
187
188  // Verify the state of cellular network and modify internal state.
189  virtual void EvaluateCellularNetwork(const NetworkState* network);
190  // PickNextState selects the desired state based on the current state of the
191  // modem and the activator.  It does not transition to this state however.
192  PlanActivationState PickNextState(const NetworkState* network,
193                                    std::string* error_description) const;
194  // One of PickNext*State are called in PickNextState based on whether the
195  // modem is online or not.
196  PlanActivationState PickNextOnlineState(const NetworkState* network) const;
197  PlanActivationState PickNextOfflineState(const NetworkState* network) const;
198  // Check the current cellular network for error conditions.
199  bool GotActivationError(const NetworkState* network,
200                          std::string* error) const;
201  // Sends status updates to WebUI page.
202  void UpdatePage(const NetworkState* network,
203                  const std::string& error_description);
204
205  // Callback used to handle an activation error.
206  void HandleActivationFailure(
207      const std::string& service_path,
208      PlanActivationState new_state,
209      const std::string& error_name,
210      scoped_ptr<base::DictionaryValue> error_data);
211
212  // Request cellular activation for |network|.
213  // On success, |success_callback| will be called.
214  // On failure, |error_callback| will be called.
215  virtual void RequestCellularActivation(
216      const NetworkState* network,
217      const base::Closure& success_callback,
218      const network_handler::ErrorCallback& error_callback);
219
220  // Changes internal state.
221  virtual void ChangeState(const NetworkState* network,
222                           PlanActivationState new_state,
223                           std::string error_description);
224  // Resets network devices after cellular activation process.
225  void CompleteActivation();
226  // Disables SSL certificate revocation checking mechanism. In the case
227  // where captive portal connection is the only one present, such revocation
228  // checks could prevent payment portal page from loading.
229  void DisableCertRevocationChecking();
230  // Reenables SSL certificate revocation checking mechanism.
231  void ReEnableCertRevocationChecking();
232  // Return error message for a given code.
233  std::string GetErrorMessage(const std::string& code) const;
234
235  // Performs activation state cellular device evaluation.
236  // Returns false if device activation failed. In this case |error|
237  // will contain error message to be reported to Web UI.
238  static bool EvaluateCellularDeviceState(bool* report_status,
239                                          std::string* state,
240                                          std::string* error);
241  // Starts the OTASP timeout timer.  If the timer fires, we'll force a
242  // disconnect/reconnect cycle on this network.
243  virtual void StartOTASPTimer();
244
245  // Records information that cellular plan payment has happened.
246  virtual void SignalCellularPlanPayment();
247
248  // Returns true if cellular plan payment has been recorded recently.
249  virtual bool HasRecentCellularPlanPayment() const;
250
251  static const char* GetStateDescription(PlanActivationState state);
252
253  scoped_refptr<CellularConfigDocument> cellular_config_;
254  // Internal handler state.
255  PlanActivationState state_;
256  // MEID of cellular device to activate.
257  std::string meid_;
258  // ICCID of the SIM card on cellular device to activate.
259  std::string iccid_;
260  // Service path of network being activated. Note that the path can change
261  // during the activation process while still representing the same service.
262  std::string service_path_;
263  // Device on which the network service is activated. While the service path
264  // can change during activation due to modem resets, the device path stays
265  // the same.
266  std::string device_path_;
267  // Flags that controls if cert_checks needs to be restored
268  // after the activation of cellular network.
269  bool reenable_cert_check_;
270  // True if activation process has been terminated.
271  bool terminated_;
272  // True if an asynchronous activation request was dispatched to Shill
273  // but the succcess or failure of the request is yet unknown.
274  bool pending_activation_request_;
275  // Connection retry counter.
276  int connection_retry_count_;
277  // Counters for how many times we've tried each OTASP step.
278  int initial_OTASP_attempts_;
279  int trying_OTASP_attempts_;
280  int final_OTASP_attempts_;
281  // Payment portal reload/reconnect attempt count.
282  int payment_reconnect_count_;
283  // Timer that monitors how long we spend in error-prone states.
284  base::RepeatingTimer<MobileActivator> state_duration_timer_;
285
286  // State we will return to if we are disconnected.
287  PlanActivationState post_reconnect_state_;
288  // Called to continue the reconnect attempt.
289  base::RepeatingTimer<MobileActivator> continue_reconnect_timer_;
290  // Called when the reconnect attempt times out.
291  base::OneShotTimer<MobileActivator> reconnect_timeout_timer_;
292  // Cellular plan payment time.
293  base::Time cellular_plan_payment_time_;
294
295  ObserverList<Observer> observers_;
296  base::WeakPtrFactory<MobileActivator> weak_ptr_factory_;
297
298  DISALLOW_COPY_AND_ASSIGN(MobileActivator);
299};
300
301}  // namespace chromeos
302
303#endif  // CHROME_BROWSER_CHROMEOS_MOBILE_MOBILE_ACTIVATOR_H_
304