Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(321)

Side by Side Diff: chrome/browser/ui/webui/chromeos/mobile_setup_ui.cc

Issue 10456045: Refactored mobile activation engine outside of WebUI handler in order to expose its state to other … (Closed) Base URL: svn://svn.chromium.org/chrome/trunk/src
Patch Set: updates Created 8 years, 6 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
OLDNEW
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved. 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 2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file. 3 // found in the LICENSE file.
4 4
5 #include "chrome/browser/ui/webui/chromeos/mobile_setup_ui.h" 5 #include "chrome/browser/ui/webui/chromeos/mobile_setup_ui.h"
6 6
7 #include <algorithm> 7 #include <algorithm>
8 #include <map> 8 #include <map>
9 #include <string> 9 #include <string>
10 10
11 #include "base/bind.h" 11 #include "base/bind.h"
12 #include "base/bind_helpers.h" 12 #include "base/bind_helpers.h"
13 #include "base/file_util.h" 13 #include "base/file_util.h"
14 #include "base/json/json_reader.h"
15 #include "base/json/json_writer.h" 14 #include "base/json/json_writer.h"
16 #include "base/logging.h" 15 #include "base/logging.h"
17 #include "base/memory/ref_counted_memory.h" 16 #include "base/memory/ref_counted_memory.h"
18 #include "base/message_loop.h" 17 #include "base/message_loop.h"
19 #include "base/metrics/histogram.h" 18 #include "base/metrics/histogram.h"
20 #include "base/string_piece.h" 19 #include "base/string_piece.h"
21 #include "base/string_util.h" 20 #include "base/string_util.h"
22 #include "base/timer.h"
23 #include "base/utf_string_conversions.h" 21 #include "base/utf_string_conversions.h"
24 #include "base/values.h" 22 #include "base/values.h"
25 #include "chrome/browser/browser_process.h"
26 #include "chrome/browser/chromeos/cros/cros_library.h" 23 #include "chrome/browser/chromeos/cros/cros_library.h"
27 #include "chrome/browser/chromeos/cros/network_library.h" 24 #include "chrome/browser/chromeos/cros/network_library.h"
28 #include "chrome/browser/prefs/pref_service.h" 25 #include "chrome/browser/chromeos/mobile/mobile_activator.h"
29 #include "chrome/browser/profiles/profile.h" 26 #include "chrome/browser/profiles/profile.h"
30 #include "chrome/browser/ui/browser_list.h" 27 #include "chrome/browser/ui/browser_list.h"
31 #include "chrome/browser/ui/webui/chrome_url_data_manager.h" 28 #include "chrome/browser/ui/webui/chrome_url_data_manager.h"
32 #include "chrome/common/jstemplate_builder.h" 29 #include "chrome/common/jstemplate_builder.h"
33 #include "chrome/common/pref_names.h" 30 #include "chrome/common/pref_names.h"
34 #include "chrome/common/render_messages.h" 31 #include "chrome/common/render_messages.h"
35 #include "chrome/common/url_constants.h" 32 #include "chrome/common/url_constants.h"
36 #include "content/public/browser/browser_thread.h" 33 #include "content/public/browser/browser_thread.h"
37 #include "content/public/browser/render_view_host_observer.h" 34 #include "content/public/browser/render_view_host_observer.h"
38 #include "content/public/browser/web_contents.h" 35 #include "content/public/browser/web_contents.h"
39 #include "content/public/browser/web_ui.h" 36 #include "content/public/browser/web_ui.h"
40 #include "content/public/browser/web_ui_message_handler.h" 37 #include "content/public/browser/web_ui_message_handler.h"
41 #include "googleurl/src/gurl.h" 38 #include "googleurl/src/gurl.h"
42 #include "grit/browser_resources.h" 39 #include "grit/browser_resources.h"
43 #include "grit/chromium_strings.h" 40 #include "grit/chromium_strings.h"
44 #include "grit/generated_resources.h" 41 #include "grit/generated_resources.h"
45 #include "grit/locale_settings.h" 42 #include "grit/locale_settings.h"
46 #include "ui/base/l10n/l10n_util.h" 43 #include "ui/base/l10n/l10n_util.h"
47 #include "ui/base/layout.h" 44 #include "ui/base/layout.h"
48 #include "ui/base/resource/resource_bundle.h" 45 #include "ui/base/resource/resource_bundle.h"
49 46
47 using chromeos::CellularNetwork;
48 using chromeos::CrosLibrary;
49 using chromeos::MobileActivator;
50 using content::BrowserThread; 50 using content::BrowserThread;
51 using content::RenderViewHost; 51 using content::RenderViewHost;
52 using content::WebContents; 52 using content::WebContents;
53 using content::WebUIMessageHandler; 53 using content::WebUIMessageHandler;
54 54
55 namespace { 55 namespace {
56 56
57 // Host page JS API function names. 57 // Host page JS API function names.
58 const char kJsApiStartActivation[] = "startActivation"; 58 const char kJsApiStartActivation[] = "startActivation";
59 const char kJsApiSetTransactionStatus[] = "setTransactionStatus"; 59 const char kJsApiSetTransactionStatus[] = "setTransactionStatus";
60 const char kJsApiPaymentPortalLoad[] = "paymentPortalLoad"; 60 const char kJsApiPaymentPortalLoad[] = "paymentPortalLoad";
61 const char kJsApiResultOK[] = "ok"; 61 const char kJsApiResultOK[] = "ok";
62 62
63 const char kJsDeviceStatusChangedCallback[] = 63 const char kJsDeviceStatusChangedCallback[] =
64 "mobile.MobileSetup.deviceStateChanged"; 64 "mobile.MobileSetup.deviceStateChanged";
65 const char kJsPortalFrameLoadFailedCallback[] = 65 const char kJsPortalFrameLoadFailedCallback[] =
66 "mobile.MobileSetup.portalFrameLoadError"; 66 "mobile.MobileSetup.portalFrameLoadError";
67 const char kJsPortalFrameLoadCompletedCallback[] = 67 const char kJsPortalFrameLoadCompletedCallback[] =
68 "mobile.MobileSetup.portalFrameLoadCompleted"; 68 "mobile.MobileSetup.portalFrameLoadCompleted";
69 69
70 // Error codes matching codes defined in the cellular config file.
71 const char kErrorDefault[] = "default";
72 const char kErrorBadConnectionPartial[] = "bad_connection_partial";
73 const char kErrorBadConnectionActivated[] = "bad_connection_activated";
74 const char kErrorRoamingOnConnection[] = "roaming_connection";
75 const char kErrorNoEVDO[] = "no_evdo";
76 const char kErrorRoamingActivation[] = "roaming_activation";
77 const char kErrorRoamingPartiallyActivated[] = "roaming_partially_activated";
78 const char kErrorNoService[] = "no_service";
79 const char kErrorDisabled[] = "disabled";
80 const char kErrorNoDevice[] = "no_device";
81 const char kFailedPaymentError[] = "failed_payment";
82 const char kFailedConnectivity[] = "connectivity";
83 const char kErrorAlreadyRunning[] = "already_running";
84
85 // Cellular configuration file path.
86 const char kCellularConfigPath[] =
87 "/usr/share/chromeos-assets/mobile/mobile_config.json";
88
89 // Cellular config file field names.
90 const char kVersionField[] = "version";
91 const char kErrorsField[] = "errors";
92
93 // Number of times we will retry to restart the activation process in case
94 // there is no connectivity in the restricted pool.
95 const int kMaxActivationAttempt = 3;
96 // Number of times we will retry to reconnect if connection fails.
97 const int kMaxConnectionRetry = 10;
98 // Number of times we will retry to reconnect and reload payment portal page.
99 const int kMaxPortalReconnectCount = 5;
100 // Number of times we will retry to reconnect if connection fails.
101 const int kMaxConnectionRetryOTASP = 30;
102 // Number of times we will retry to reconnect after payment is processed.
103 const int kMaxReconnectAttemptOTASP = 30;
104 // Reconnect retry delay (after payment is processed).
105 const int kPostPaymentReconnectDelayMS = 30000; // 30s.
106 // Connection timeout in seconds.
107 const int kConnectionTimeoutSeconds = 45;
108 // Reconnect delay.
109 const int kReconnectDelayMS = 3000;
110 // Reconnect timer delay.
111 const int kReconnectTimerDelayMS = 5000;
112 // Reconnect delay after previous failure.
113 const int kFailedReconnectDelayMS = 10000;
114 // Retry delay after failed OTASP attempt.
115 const int kOTASPRetryDelay = 20000;
116
117 chromeos::CellularNetwork* GetCellularNetwork() {
118 chromeos::NetworkLibrary* lib = chromeos::CrosLibrary::Get()->
119 GetNetworkLibrary();
120 if (lib->cellular_networks().begin() != lib->cellular_networks().end()) {
121 return *(lib->cellular_networks().begin());
122 }
123 return NULL;
124 }
125
126 chromeos::CellularNetwork* GetCellularNetwork(
127 const std::string& service_path) {
128 return chromeos::CrosLibrary::Get()->
129 GetNetworkLibrary()->FindCellularNetworkByPath(service_path);
130 }
131
132 } // namespace 70 } // namespace
133 71
134 // Observes IPC messages from the rederer and notifies JS if frame loading error 72 // Observes IPC messages from the rederer and notifies JS if frame loading error
135 // appears. 73 // appears.
136 class PortalFrameLoadObserver : public content::RenderViewHostObserver { 74 class PortalFrameLoadObserver : public content::RenderViewHostObserver {
137 public: 75 public:
138 PortalFrameLoadObserver(const base::WeakPtr<MobileSetupUI>& parent, 76 PortalFrameLoadObserver(const base::WeakPtr<MobileSetupUI>& parent,
139 RenderViewHost* host) 77 RenderViewHost* host)
140 : content::RenderViewHostObserver(host), parent_(parent) { 78 : content::RenderViewHostObserver(host), parent_(parent) {
141 Send(new ChromeViewMsg_StartFrameSniffer(routing_id(), 79 Send(new ChromeViewMsg_StartFrameSniffer(routing_id(),
(...skipping 27 matching lines...) Expand all
169 return; 107 return;
170 108
171 parent_->web_ui()->CallJavascriptFunction( 109 parent_->web_ui()->CallJavascriptFunction(
172 kJsPortalFrameLoadCompletedCallback); 110 kJsPortalFrameLoadCompletedCallback);
173 } 111 }
174 112
175 base::WeakPtr<MobileSetupUI> parent_; 113 base::WeakPtr<MobileSetupUI> parent_;
176 DISALLOW_COPY_AND_ASSIGN(PortalFrameLoadObserver); 114 DISALLOW_COPY_AND_ASSIGN(PortalFrameLoadObserver);
177 }; 115 };
178 116
179 class CellularConfigDocument
180 : public base::RefCountedThreadSafe<CellularConfigDocument> {
181 public:
182 CellularConfigDocument() {}
183
184 // Return error message for a given code.
185 std::string GetErrorMessage(const std::string& code);
186 void LoadCellularConfigFile();
187 const std::string& version() { return version_; }
188
189 private:
190 typedef std::map<std::string, std::string> ErrorMap;
191
192 void SetErrorMap(const ErrorMap& map);
193 bool LoadFromFile(const FilePath& config_path);
194
195 std::string version_;
196 ErrorMap error_map_;
197 base::Lock config_lock_;
198
199 DISALLOW_COPY_AND_ASSIGN(CellularConfigDocument);
200 };
201
202 class MobileSetupUIHTMLSource : public ChromeURLDataManager::DataSource { 117 class MobileSetupUIHTMLSource : public ChromeURLDataManager::DataSource {
203 public: 118 public:
204 explicit MobileSetupUIHTMLSource(const std::string& service_path); 119 explicit MobileSetupUIHTMLSource();
rkc 2012/06/05 21:48:03 no explicit.
zel 2012/06/05 23:02:35 Done.
205 120
206 // Called when the network layer has requested a resource underneath 121 // Called when the network layer has requested a resource underneath
207 // the path we registered. 122 // the path we registered.
208 virtual void StartDataRequest(const std::string& path, 123 virtual void StartDataRequest(const std::string& path,
209 bool is_incognito, 124 bool is_incognito,
210 int request_id); 125 int request_id);
211 virtual std::string GetMimeType(const std::string&) const { 126 virtual std::string GetMimeType(const std::string&) const {
212 return "text/html"; 127 return "text/html";
213 } 128 }
214 129
215 private: 130 private:
216 virtual ~MobileSetupUIHTMLSource() {} 131 virtual ~MobileSetupUIHTMLSource() {}
217 132
218 std::string service_path_;
219 DISALLOW_COPY_AND_ASSIGN(MobileSetupUIHTMLSource); 133 DISALLOW_COPY_AND_ASSIGN(MobileSetupUIHTMLSource);
220 }; 134 };
221 135
222 // The handler for Javascript messages related to the "register" view. 136 // The handler for Javascript messages related to the "register" view.
223 class MobileSetupHandler 137 class MobileSetupHandler
224 : public WebUIMessageHandler, 138 : public WebUIMessageHandler,
225 public chromeos::NetworkLibrary::NetworkManagerObserver, 139 public MobileActivator::Observer,
226 public chromeos::NetworkLibrary::NetworkObserver,
227 public base::SupportsWeakPtr<MobileSetupHandler> { 140 public base::SupportsWeakPtr<MobileSetupHandler> {
228 public: 141 public:
229 explicit MobileSetupHandler(const std::string& service_path); 142 explicit MobileSetupHandler();
rkc 2012/06/05 21:48:03 no explicit.
zel 2012/06/05 23:02:35 Done.
230 virtual ~MobileSetupHandler(); 143 virtual ~MobileSetupHandler();
231 144
232 // Init work after Attach.
233 void StartActivationOnUIThread();
234
235 // WebUIMessageHandler implementation. 145 // WebUIMessageHandler implementation.
236 virtual void RegisterMessages() OVERRIDE; 146 virtual void RegisterMessages() OVERRIDE;
237 147
238 // NetworkLibrary::NetworkManagerObserver implementation.
239 virtual void OnNetworkManagerChanged(chromeos::NetworkLibrary* obj) OVERRIDE;
240 // NetworkLibrary::NetworkObserver implementation.
241 virtual void OnNetworkChanged(chromeos::NetworkLibrary* obj,
242 const chromeos::Network* network) OVERRIDE;
243
244 private: 148 private:
245 typedef enum PlanActivationState { 149 // Changes internal state.
246 PLAN_ACTIVATION_PAGE_LOADING = -1, 150 void OnActivationStateChanged(CellularNetwork* network,
247 PLAN_ACTIVATION_START = 0, 151 MobileActivator::PlanActivationState new_state,
248 PLAN_ACTIVATION_TRYING_OTASP = 1, 152 const std::string& error_description);
249 PLAN_ACTIVATION_RECONNECTING_OTASP_TRY = 2,
250 PLAN_ACTIVATION_INITIATING_ACTIVATION = 3,
251 PLAN_ACTIVATION_RECONNECTING = 4,
252 PLAN_ACTIVATION_PAYMENT_PORTAL_LOADING = 5,
253 PLAN_ACTIVATION_SHOWING_PAYMENT = 6,
254 PLAN_ACTIVATION_RECONNECTING_PAYMENT = 7,
255 PLAN_ACTIVATION_DELAY_OTASP = 8,
256 PLAN_ACTIVATION_START_OTASP = 9,
257 PLAN_ACTIVATION_OTASP = 10,
258 PLAN_ACTIVATION_RECONNECTING_OTASP = 11,
259 PLAN_ACTIVATION_DONE = 12,
260 PLAN_ACTIVATION_ERROR = 0xFF,
261 } PlanActivationState;
262 153
263 // Handlers for JS WebUI messages. 154 // Handlers for JS WebUI messages.
264 void HandleSetTransactionStatus(const ListValue* args); 155 void HandleSetTransactionStatus(const ListValue* args);
265 void HandleStartActivation(const ListValue* args); 156 void HandleStartActivation(const ListValue* args);
266 void HandlePaymentPortalLoad(const ListValue* args); 157 void HandlePaymentPortalLoad(const ListValue* args);
267 void SetTransactionStatus(const std::string& status);
268 // Starts activation.
269 void StartActivation();
270 // Retried OTASP.
271 void RetryOTASP();
272 // Continues activation process. This method is called after we disconnect
273 // due to detected connectivity issue to kick off reconnection.
274 void ContinueConnecting(int delay);
275 158
276 // Sends message to host registration page with system/user info data. 159 // Sends message to host registration page with system/user info data.
277 void SendDeviceInfo(); 160 void SendDeviceInfo();
278 161
279 // Callback for when |reconnect_timer_| fires.
280 void ReconnectTimerFired();
281 // Starts OTASP process.
282 void StartOTASP();
283 // Checks if we need to reconnect due to failed connection attempt.
284 bool NeedsReconnecting(chromeos::CellularNetwork* network,
285 PlanActivationState* new_state,
286 std::string* error_description);
287 // Disconnect from network.
288 void DisconnectFromNetwork(chromeos::CellularNetwork* network);
289 // Connects to cellular network, resets connection timer.
290 bool ConnectToNetwork(chromeos::CellularNetwork* network, int delay);
291 // Forces disconnect / reconnect when we detect portal connectivity issues.
292 void ForceReconnect(chromeos::CellularNetwork* network, int delay);
293 // Reports connection timeout.
294 bool ConnectionTimeout();
295 // Verify the state of cellular network and modify internal state.
296 void EvaluateCellularNetwork(chromeos::CellularNetwork* network);
297 // Check the current cellular network for error conditions.
298 bool GotActivationError(chromeos::CellularNetwork* network,
299 std::string* error);
300 // Sends status updates to WebUI page.
301 void UpdatePage(chromeos::CellularNetwork* network,
302 const std::string& error_description);
303 // Changes internal state.
304 void ChangeState(chromeos::CellularNetwork* network,
305 PlanActivationState new_state,
306 const std::string& error_description);
307 // Prepares network devices for cellular activation process.
308 void SetupActivationProcess(chromeos::CellularNetwork* network);
309 // Disables ethernet and wifi newtorks since they interefere with
310 // detection of restricted pool on cellular side.
311 void DisableOtherNetworks();
312 // Resets network devices after cellular activation process.
313 // |network| should be NULL if the activation process failed.
314 void CompleteActivation(chromeos::CellularNetwork* network);
315 // Control routines for handling other types of connections during
316 // cellular activation.
317 void ReEnableOtherConnections();
318 // Return error message for a given code.
319 std::string GetErrorMessage(const std::string& code);
320
321 // Converts the currently active CellularNetwork device into a JS object. 162 // Converts the currently active CellularNetwork device into a JS object.
322 static void GetDeviceInfo(chromeos::CellularNetwork* network, 163 static void GetDeviceInfo(CellularNetwork* network,
323 DictionaryValue* value); 164 DictionaryValue* value);
324 static bool ShouldReportDeviceState(std::string* state, std::string* error);
325
326 // Performs activation state cellular device evaluation.
327 // Returns false if device activation failed. In this case |error|
328 // will contain error message to be reported to Web UI.
329 static bool EvaluateCellularDeviceState(bool* report_status,
330 std::string* state,
331 std::string* error);
332
333 // Returns next reconnection state based on the current activation phase.
334 static PlanActivationState GetNextReconnectState(PlanActivationState state);
335 static const char* GetStateDescription(PlanActivationState state);
336
337 scoped_refptr<CellularConfigDocument> cellular_config_;
338 // Internal handler state.
339 PlanActivationState state_;
340 std::string service_path_;
341 // Flags that control if wifi and ethernet connection needs to be restored
342 // after the activation of cellular network.
343 bool reenable_wifi_;
344 bool reenable_ethernet_;
345 bool reenable_cert_check_;
346 bool evaluating_;
347 // True if we think that another tab is already running activation.
348 bool already_running_;
349 // Connection retry counter.
350 int connection_retry_count_;
351 // Post payment reconnect wait counters.
352 int reconnect_wait_count_;
353 // Payment portal reload/reconnect attempt count.
354 int payment_reconnect_count_;
355 // Activation retry attempt count;
356 int activation_attempt_;
357 // Connection start time.
358 base::Time connection_start_time_;
359 // Timer that monitors reconnection timeouts.
360 base::RepeatingTimer<MobileSetupHandler> reconnect_timer_;
361 165
362 DISALLOW_COPY_AND_ASSIGN(MobileSetupHandler); 166 DISALLOW_COPY_AND_ASSIGN(MobileSetupHandler);
363 }; 167 };
364 168
365 //////////////////////////////////////////////////////////////////////////////// 169 ////////////////////////////////////////////////////////////////////////////////
366 // 170 //
367 // CellularConfigDocument
368 //
369 ////////////////////////////////////////////////////////////////////////////////
370
371 std::string CellularConfigDocument::GetErrorMessage(const std::string& code) {
372 base::AutoLock create(config_lock_);
373 ErrorMap::iterator iter = error_map_.find(code);
374 if (iter == error_map_.end())
375 return code;
376 return iter->second;
377 }
378
379 void CellularConfigDocument::LoadCellularConfigFile() {
380 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
381 // Load partner customization startup manifest if it is available.
382 FilePath config_path(kCellularConfigPath);
383 if (!file_util::PathExists(config_path))
384 return;
385
386 if (LoadFromFile(config_path)) {
387 DVLOG(1) << "Cellular config file loaded: " << kCellularConfigPath;
388 } else {
389 LOG(ERROR) << "Error loading cellular config file: " <<
390 kCellularConfigPath;
391 }
392 }
393
394 bool CellularConfigDocument::LoadFromFile(const FilePath& config_path) {
395 std::string config;
396 if (!file_util::ReadFileToString(config_path, &config))
397 return false;
398
399 scoped_ptr<Value> root(
400 base::JSONReader::Read(config, base::JSON_ALLOW_TRAILING_COMMAS));
401 DCHECK(root.get() != NULL);
402 if (!root.get() || root->GetType() != Value::TYPE_DICTIONARY) {
403 LOG(WARNING) << "Bad cellular config file";
404 return false;
405 }
406
407 DictionaryValue* root_dict = static_cast<DictionaryValue*>(root.get());
408 if (!root_dict->GetString(kVersionField, &version_)) {
409 LOG(WARNING) << "Cellular config file missing version";
410 return false;
411 }
412 ErrorMap error_map;
413 DictionaryValue* errors = NULL;
414 if (!root_dict->GetDictionary(kErrorsField, &errors))
415 return false;
416 for (DictionaryValue::key_iterator keys = errors->begin_keys();
417 keys != errors->end_keys();
418 ++keys) {
419 std::string value;
420 if (!errors->GetString(*keys, &value)) {
421 LOG(WARNING) << "Bad cellular config error value";
422 return false;
423 }
424 error_map.insert(ErrorMap::value_type(*keys, value));
425 }
426 SetErrorMap(error_map);
427 return true;
428 }
429
430 void CellularConfigDocument::SetErrorMap(
431 const ErrorMap& map) {
432 base::AutoLock create(config_lock_);
433 error_map_.clear();
434 error_map_.insert(map.begin(), map.end());
435 }
436
437 ////////////////////////////////////////////////////////////////////////////////
438 //
439 // MobileSetupUIHTMLSource 171 // MobileSetupUIHTMLSource
440 // 172 //
441 //////////////////////////////////////////////////////////////////////////////// 173 ////////////////////////////////////////////////////////////////////////////////
442 174
443 MobileSetupUIHTMLSource::MobileSetupUIHTMLSource( 175 MobileSetupUIHTMLSource::MobileSetupUIHTMLSource()
444 const std::string& service_path) 176 : DataSource(chrome::kChromeUIMobileSetupHost, MessageLoop::current()) {
445 : DataSource(chrome::kChromeUIMobileSetupHost, MessageLoop::current()),
446 service_path_(service_path) {
447 } 177 }
448 178
449 void MobileSetupUIHTMLSource::StartDataRequest(const std::string& path, 179 void MobileSetupUIHTMLSource::StartDataRequest(const std::string& path,
450 bool is_incognito, 180 bool is_incognito,
451 int request_id) { 181 int request_id) {
452 chromeos::CellularNetwork* network = GetCellularNetwork(service_path_); 182 CellularNetwork* network = !path.size() ? NULL :
453 // If we are activating, shutting down, or logging in, |network| may not 183 CrosLibrary::Get()->
454 // be available. 184 GetNetworkLibrary()->FindCellularNetworkByPath(path);
455 if (!network || !network->SupportsActivation()) { 185 if (!network || !network->SupportsActivation()) {
186 LOG(WARNING) << "Can't find device to activate for service path " << path;
456 scoped_refptr<base::RefCountedBytes> html_bytes(new base::RefCountedBytes); 187 scoped_refptr<base::RefCountedBytes> html_bytes(new base::RefCountedBytes);
457 SendResponse(request_id, html_bytes); 188 SendResponse(request_id, html_bytes);
458 return; 189 return;
459 } 190 }
191
192 LOG(WARNING) << "Activating mobile service " << path;
460 DictionaryValue strings; 193 DictionaryValue strings;
461 strings.SetString("title", l10n_util::GetStringUTF16(IDS_MOBILE_SETUP_TITLE)); 194 strings.SetString("title", l10n_util::GetStringUTF16(IDS_MOBILE_SETUP_TITLE));
462 strings.SetString("connecting_header", 195 strings.SetString("connecting_header",
463 l10n_util::GetStringFUTF16(IDS_MOBILE_CONNECTING_HEADER, 196 l10n_util::GetStringFUTF16(IDS_MOBILE_CONNECTING_HEADER,
464 network ? UTF8ToUTF16(network->name()) : string16())); 197 network ? UTF8ToUTF16(network->name()) : string16()));
465 strings.SetString("error_header", 198 strings.SetString("error_header",
466 l10n_util::GetStringUTF16(IDS_MOBILE_ERROR_HEADER)); 199 l10n_util::GetStringUTF16(IDS_MOBILE_ERROR_HEADER));
467 strings.SetString("activating_header", 200 strings.SetString("activating_header",
468 l10n_util::GetStringUTF16(IDS_MOBILE_ACTIVATING_HEADER)); 201 l10n_util::GetStringUTF16(IDS_MOBILE_ACTIVATING_HEADER));
469 strings.SetString("completed_header", 202 strings.SetString("completed_header",
(...skipping 18 matching lines...) Expand all
488 &strings); 221 &strings);
489 222
490 SendResponse(request_id, base::RefCountedString::TakeString(&full_html)); 223 SendResponse(request_id, base::RefCountedString::TakeString(&full_html));
491 } 224 }
492 225
493 //////////////////////////////////////////////////////////////////////////////// 226 ////////////////////////////////////////////////////////////////////////////////
494 // 227 //
495 // MobileSetupHandler 228 // MobileSetupHandler
496 // 229 //
497 //////////////////////////////////////////////////////////////////////////////// 230 ////////////////////////////////////////////////////////////////////////////////
498 MobileSetupHandler::MobileSetupHandler(const std::string& service_path) 231 MobileSetupHandler::MobileSetupHandler() {
499 : cellular_config_(new CellularConfigDocument()), 232 MobileActivator::GetInstance()->AddObserver(this);
500 state_(PLAN_ACTIVATION_PAGE_LOADING),
501 service_path_(service_path),
502 reenable_wifi_(false),
503 reenable_ethernet_(false),
504 reenable_cert_check_(false),
505 evaluating_(false),
506 already_running_(false),
507 connection_retry_count_(0),
508 reconnect_wait_count_(0),
509 payment_reconnect_count_(0),
510 activation_attempt_(0) {
511 } 233 }
512 234
513 MobileSetupHandler::~MobileSetupHandler() { 235 MobileSetupHandler::~MobileSetupHandler() {
514 reconnect_timer_.Stop(); 236 MobileActivator::GetInstance()->RemoveObserver(this);
515 chromeos::NetworkLibrary* lib = 237 MobileActivator::GetInstance()->TerminateActivation();
516 chromeos::CrosLibrary::Get()->GetNetworkLibrary(); 238 }
517 lib->RemoveNetworkManagerObserver(this); 239
518 lib->RemoveObserverForAllNetworks(this); 240 void MobileSetupHandler::OnActivationStateChanged(
519 if (lib->IsLocked()) 241 CellularNetwork* network,
520 lib->Unlock(); 242 MobileActivator::PlanActivationState state,
521 ReEnableOtherConnections(); 243 const std::string& error_description) {
244 if (!web_ui())
245 return;
246
247 DictionaryValue device_dict;
248 if (network)
249 GetDeviceInfo(network, &device_dict);
250 device_dict.SetInteger("state", state);
251 if (error_description.length())
252 device_dict.SetString("error", error_description);
253 web_ui()->CallJavascriptFunction(
254 kJsDeviceStatusChangedCallback, device_dict);
522 } 255 }
523 256
524 void MobileSetupHandler::RegisterMessages() { 257 void MobileSetupHandler::RegisterMessages() {
525 web_ui()->RegisterMessageCallback(kJsApiStartActivation, 258 web_ui()->RegisterMessageCallback(kJsApiStartActivation,
526 base::Bind(&MobileSetupHandler::HandleStartActivation, 259 base::Bind(&MobileSetupHandler::HandleStartActivation,
527 base::Unretained(this))); 260 base::Unretained(this)));
528 web_ui()->RegisterMessageCallback(kJsApiSetTransactionStatus, 261 web_ui()->RegisterMessageCallback(kJsApiSetTransactionStatus,
529 base::Bind(&MobileSetupHandler::HandleSetTransactionStatus, 262 base::Bind(&MobileSetupHandler::HandleSetTransactionStatus,
530 base::Unretained(this))); 263 base::Unretained(this)));
531 web_ui()->RegisterMessageCallback(kJsApiPaymentPortalLoad, 264 web_ui()->RegisterMessageCallback(kJsApiPaymentPortalLoad,
532 base::Bind(&MobileSetupHandler::HandlePaymentPortalLoad, 265 base::Bind(&MobileSetupHandler::HandlePaymentPortalLoad,
533 base::Unretained(this))); 266 base::Unretained(this)));
534 } 267 }
535 268
536 void MobileSetupHandler::OnNetworkManagerChanged( 269 void MobileSetupHandler::HandleStartActivation(const ListValue* args) {
537 chromeos::NetworkLibrary* cros) { 270 if (!web_ui())
538 if (state_ == PLAN_ACTIVATION_PAGE_LOADING)
539 return; 271 return;
540 // Note that even though we get here when the service has
541 // reappeared after disappearing earlier in the activation
542 // process, there's no need to re-establish the NetworkObserver,
543 // because the service path remains the same.
544 EvaluateCellularNetwork(GetCellularNetwork(service_path_));
545 }
546 272
547 void MobileSetupHandler::OnNetworkChanged(chromeos::NetworkLibrary* cros, 273 std::string path = web_ui()->GetWebContents()->GetURL().path();
548 const chromeos::Network* network) { 274 if (!path.size())
549 if (state_ == PLAN_ACTIVATION_PAGE_LOADING)
550 return; 275 return;
551 DCHECK(network && network->type() == chromeos::TYPE_CELLULAR);
552 EvaluateCellularNetwork(GetCellularNetwork(network->service_path()));
553 }
554 276
555 void MobileSetupHandler::HandleStartActivation(const ListValue* args) { 277 LOG(WARNING) << "Starting activation for service " << path;
556 BrowserThread::PostTaskAndReply(BrowserThread::FILE, FROM_HERE, 278
557 base::Bind(&CellularConfigDocument::LoadCellularConfigFile, 279 MobileActivator::GetInstance()->InitiateActivation(path.substr(1));
558 cellular_config_.get()),
559 base::Bind(&MobileSetupHandler::StartActivationOnUIThread, AsWeakPtr()));
560 } 280 }
561 281
562 void MobileSetupHandler::HandleSetTransactionStatus(const ListValue* args) { 282 void MobileSetupHandler::HandleSetTransactionStatus(const ListValue* args) {
563 const size_t kSetTransactionStatusParamCount = 1; 283 const size_t kSetTransactionStatusParamCount = 1;
564 if (args->GetSize() != kSetTransactionStatusParamCount) 284 if (args->GetSize() != kSetTransactionStatusParamCount)
565 return; 285 return;
566 // Get change callback function name. 286 // Get change callback function name.
567 std::string status; 287 std::string status;
568 if (!args->GetString(0, &status)) 288 if (!args->GetString(0, &status))
569 return; 289 return;
570 BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, 290
571 base::Bind(&MobileSetupHandler::SetTransactionStatus, AsWeakPtr(), 291 MobileActivator::GetInstance()->OnSetTransactionStatus(
572 status)); 292 LowerCaseEqualsASCII(status, kJsApiResultOK));
573 } 293 }
574 294
575 void MobileSetupHandler::HandlePaymentPortalLoad(const ListValue* args) { 295 void MobileSetupHandler::HandlePaymentPortalLoad(const ListValue* args) {
576 const size_t kPaymentPortalLoadParamCount = 1; 296 const size_t kPaymentPortalLoadParamCount = 1;
577 if (args->GetSize() != kPaymentPortalLoadParamCount) 297 if (args->GetSize() != kPaymentPortalLoadParamCount)
578 return; 298 return;
579 // Get change callback function name. 299 // Get change callback function name.
580 std::string result; 300 std::string result;
581 if (!args->GetString(0, &result)) 301 if (!args->GetString(0, &result))
582 return; 302 return;
583 chromeos::CellularNetwork* network = GetCellularNetwork(service_path_); 303
584 if (!network) { 304 MobileActivator::GetInstance()->OnPortalLoaded(
585 ChangeState(NULL, PLAN_ACTIVATION_ERROR, 305 LowerCaseEqualsASCII(result, kJsApiResultOK));
586 GetErrorMessage(kErrorNoService));
587 return;
588 }
589 if (state_ == PLAN_ACTIVATION_PAYMENT_PORTAL_LOADING ||
590 state_ == PLAN_ACTIVATION_SHOWING_PAYMENT) {
591 if (LowerCaseEqualsASCII(result, kJsApiResultOK)) {
592 payment_reconnect_count_ = 0;
593 ChangeState(network, PLAN_ACTIVATION_SHOWING_PAYMENT, std::string());
594 } else {
595 payment_reconnect_count_++;
596 if (payment_reconnect_count_ > kMaxPortalReconnectCount) {
597 ChangeState(NULL, PLAN_ACTIVATION_ERROR,
598 GetErrorMessage(kErrorNoService));
599 return;
600 }
601 // Disconnect now, this should force reconnection and we will retry to
602 // load the frame containing payment portal again.
603 DisconnectFromNetwork(network);
604 }
605 } else {
606 NOTREACHED() << "Called paymentPortalLoad while in unexpected state: "
607 << GetStateDescription(state_);
608 }
609 } 306 }
610 307
611 void MobileSetupHandler::StartActivation() { 308 void MobileSetupHandler::GetDeviceInfo(CellularNetwork* network,
612 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
613 UMA_HISTOGRAM_COUNTS("Cellular.MobileSetupStart", 1);
614 chromeos::NetworkLibrary* lib =
615 chromeos::CrosLibrary::Get()->GetNetworkLibrary();
616 chromeos::CellularNetwork* network = GetCellularNetwork(service_path_);
617 // Check if we can start activation process.
618 if (!network || already_running_) {
619 std::string error;
620 if (already_running_)
621 error = kErrorAlreadyRunning;
622 else if (!lib->cellular_available())
623 error = kErrorNoDevice;
624 else if (!lib->cellular_enabled())
625 error = kErrorDisabled;
626 else
627 error = kErrorNoService;
628 ChangeState(NULL, PLAN_ACTIVATION_ERROR, GetErrorMessage(error));
629 return;
630 }
631
632 // Start monitoring network property changes.
633 lib->AddNetworkManagerObserver(this);
634 lib->RemoveObserverForAllNetworks(this);
635 lib->AddNetworkObserver(network->service_path(), this);
636 // Try to start with OTASP immediately if we have received payment recently.
637 state_ = lib->HasRecentCellularPlanPayment() ?
638 PLAN_ACTIVATION_START_OTASP :
639 PLAN_ACTIVATION_START;
640 EvaluateCellularNetwork(network);
641 }
642
643 void MobileSetupHandler::RetryOTASP() {
644 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
645 DCHECK(state_ == PLAN_ACTIVATION_DELAY_OTASP);
646 StartOTASP();
647 }
648
649 void MobileSetupHandler::ContinueConnecting(int delay) {
650 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
651 chromeos::CellularNetwork* network = GetCellularNetwork(service_path_);
652 if (network && network->connecting_or_connected()) {
653 EvaluateCellularNetwork(network);
654 } else {
655 ConnectToNetwork(network, delay);
656 }
657 }
658
659 void MobileSetupHandler::SetTransactionStatus(const std::string& status) {
660 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
661 // The payment is received, try to reconnect and check the status all over
662 // again.
663 if (LowerCaseEqualsASCII(status, kJsApiResultOK) &&
664 state_ == PLAN_ACTIVATION_SHOWING_PAYMENT) {
665 chromeos::NetworkLibrary* lib =
666 chromeos::CrosLibrary::Get()->GetNetworkLibrary();
667 lib->SignalCellularPlanPayment();
668 UMA_HISTOGRAM_COUNTS("Cellular.PaymentReceived", 1);
669 StartOTASP();
670 } else {
671 UMA_HISTOGRAM_COUNTS("Cellular.PaymentFailed", 1);
672 }
673 }
674
675 void MobileSetupHandler::StartOTASP() {
676 state_ = PLAN_ACTIVATION_START_OTASP;
677 chromeos::CellularNetwork* network = GetCellularNetwork();
678 if (network &&
679 network->connected() &&
680 network->activation_state() == chromeos::ACTIVATION_STATE_ACTIVATED) {
681 chromeos::CrosLibrary::Get()->GetNetworkLibrary()->
682 DisconnectFromNetwork(network);
683 } else {
684 EvaluateCellularNetwork(network);
685 }
686 }
687
688 void MobileSetupHandler::ReconnectTimerFired() {
689 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
690 // Permit network connection changes only in reconnecting states.
691 if (state_ != PLAN_ACTIVATION_RECONNECTING_OTASP_TRY &&
692 state_ != PLAN_ACTIVATION_RECONNECTING &&
693 state_ != PLAN_ACTIVATION_RECONNECTING_PAYMENT &&
694 state_ != PLAN_ACTIVATION_RECONNECTING_OTASP)
695 return;
696 chromeos::CellularNetwork* network = GetCellularNetwork(service_path_);
697 if (!network) {
698 // No service, try again since this is probably just transient condition.
699 LOG(WARNING) << "Service not present at reconnect attempt.";
700 }
701 EvaluateCellularNetwork(network);
702 }
703
704 void MobileSetupHandler::DisconnectFromNetwork(
705 chromeos::CellularNetwork* network) {
706 DCHECK(network);
707 LOG(INFO) << "Disconnecting from: " << network->service_path();
708 chromeos::CrosLibrary::Get()->GetNetworkLibrary()->
709 DisconnectFromNetwork(network);
710 // Disconnect will force networks to be reevaluated, so
711 // we don't want to continue processing on this path anymore.
712 evaluating_ = false;
713 }
714
715 bool MobileSetupHandler::NeedsReconnecting(
716 chromeos::CellularNetwork* network,
717 PlanActivationState* new_state,
718 std::string* error_description) {
719 DCHECK(network);
720 if (!network->failed() && !ConnectionTimeout())
721 return false;
722
723 // Try to reconnect again if reconnect failed, or if for some
724 // reasons we are still not connected after 45 seconds.
725 int max_retries = (state_ == PLAN_ACTIVATION_RECONNECTING_OTASP) ?
726 kMaxConnectionRetryOTASP : kMaxConnectionRetry;
727 if (connection_retry_count_ < max_retries) {
728 UMA_HISTOGRAM_COUNTS("Cellular.ConnectionRetry", 1);
729 ConnectToNetwork(network, kFailedReconnectDelayMS);
730 return true;
731 }
732 // We simply can't connect anymore after all these tries.
733 UMA_HISTOGRAM_COUNTS("Cellular.ConnectionFailed", 1);
734 *new_state = PLAN_ACTIVATION_ERROR;
735 *error_description = GetErrorMessage(kFailedConnectivity);
736 return false;
737 }
738
739 bool MobileSetupHandler::ConnectToNetwork(
740 chromeos::CellularNetwork* network,
741 int delay) {
742 if (network && network->connecting_or_connected())
743 return true;
744 // Permit network connection changes only in reconnecting states.
745 if (state_ != PLAN_ACTIVATION_RECONNECTING_OTASP_TRY &&
746 state_ != PLAN_ACTIVATION_RECONNECTING &&
747 state_ != PLAN_ACTIVATION_RECONNECTING_PAYMENT &&
748 state_ != PLAN_ACTIVATION_RECONNECTING_OTASP) return false;
749 if (network)
750 LOG(INFO) << "Connecting to: " << network->service_path();
751 connection_retry_count_++;
752 connection_start_time_ = base::Time::Now();
753 if (!network) {
754 LOG(WARNING) << "Connect failed."
755 << (network ? network->service_path().c_str() : "no service");
756 // If we coudn't connect during reconnection phase, try to reconnect
757 // with a delay (and try to reconnect if needed).
758 BrowserThread::PostDelayedTask(BrowserThread::UI, FROM_HERE,
759 base::Bind(&MobileSetupHandler::ContinueConnecting, AsWeakPtr(), delay),
760 base::TimeDelta::FromMilliseconds(delay));
761 return false;
762 }
763 chromeos::CrosLibrary::Get()->GetNetworkLibrary()->
764 ConnectToCellularNetwork(network);
765 return true;
766 }
767
768 void MobileSetupHandler::ForceReconnect(
769 chromeos::CellularNetwork* network,
770 int delay) {
771 DCHECK(network);
772 UMA_HISTOGRAM_COUNTS("Cellular.ActivationRetry", 1);
773 // Reset reconnect metrics.
774 connection_retry_count_ = 0;
775 connection_start_time_ = base::Time();
776 // First, disconnect...
777 LOG(INFO) << "Disconnecting from " << network->service_path();
778 chromeos::CrosLibrary::Get()->GetNetworkLibrary()->
779 DisconnectFromNetwork(network);
780 // Check the network state 3s after we disconnect to make sure.
781 BrowserThread::PostDelayedTask(BrowserThread::UI, FROM_HERE,
782 base::Bind(&MobileSetupHandler::ContinueConnecting, AsWeakPtr(), delay),
783 base::TimeDelta::FromMilliseconds(delay));
784 }
785
786 bool MobileSetupHandler::ConnectionTimeout() {
787 return (base::Time::Now() -
788 connection_start_time_).InSeconds() > kConnectionTimeoutSeconds;
789 }
790
791 void MobileSetupHandler::EvaluateCellularNetwork(
792 chromeos::CellularNetwork* network) {
793 if (!web_ui())
794 return;
795
796 PlanActivationState new_state = state_;
797 if (!network) {
798 LOG(WARNING) << "Cellular service lost";
799 if (state_ == PLAN_ACTIVATION_RECONNECTING_OTASP_TRY ||
800 state_ == PLAN_ACTIVATION_RECONNECTING ||
801 state_ == PLAN_ACTIVATION_RECONNECTING_PAYMENT ||
802 state_ == PLAN_ACTIVATION_RECONNECTING_OTASP) {
803 // This might be the legit case when service is lost after activation.
804 // We need to make sure we force reconnection as soon as it shows up.
805 LOG(INFO) << "Force service reconnection";
806 connection_start_time_ = base::Time();
807 }
808 return;
809 }
810
811 // Prevent this method from being called if it is already on the stack.
812 // This might happen on some state transitions (ie. connect, disconnect).
813 if (evaluating_)
814 return;
815 evaluating_ = true;
816 std::string error_description;
817
818 LOG(WARNING) << "Cellular:\n service=" << network->GetStateString().c_str()
819 << "\n ui=" << GetStateDescription(state_)
820 << "\n activation=" << network->GetActivationStateString().c_str()
821 << "\n error=" << network->GetErrorString().c_str()
822 << "\n setvice_path=" << network->service_path().c_str();
823 switch (state_) {
824 case PLAN_ACTIVATION_START: {
825 switch (network->activation_state()) {
826 case chromeos::ACTIVATION_STATE_ACTIVATED: {
827 if (network->disconnected()) {
828 new_state = PLAN_ACTIVATION_RECONNECTING;
829 } else if (network->connected()) {
830 if (network->restricted_pool()) {
831 new_state = PLAN_ACTIVATION_PAYMENT_PORTAL_LOADING;
832 } else {
833 new_state = PLAN_ACTIVATION_DONE;
834 }
835 }
836 break;
837 }
838 default: {
839 if (network->disconnected() ||
840 network->state() == chromeos::STATE_ACTIVATION_FAILURE) {
841 new_state = (network->activation_state() ==
842 chromeos::ACTIVATION_STATE_PARTIALLY_ACTIVATED) ?
843 PLAN_ACTIVATION_TRYING_OTASP :
844 PLAN_ACTIVATION_INITIATING_ACTIVATION;
845 } else if (network->connected()) {
846 DisconnectFromNetwork(network);
847 return;
848 }
849 break;
850 }
851 }
852 break;
853 }
854 case PLAN_ACTIVATION_START_OTASP: {
855 switch (network->activation_state()) {
856 case chromeos::ACTIVATION_STATE_PARTIALLY_ACTIVATED: {
857 if (network->disconnected()) {
858 new_state = PLAN_ACTIVATION_OTASP;
859 } else if (network->connected()) {
860 DisconnectFromNetwork(network);
861 return;
862 }
863 break;
864 }
865 case chromeos::ACTIVATION_STATE_ACTIVATED:
866 new_state = PLAN_ACTIVATION_RECONNECTING_OTASP;
867 break;
868 default: {
869 LOG(WARNING) << "Unexpected activation state for device "
870 << network->service_path().c_str();
871 break;
872 }
873 }
874 break;
875 }
876 case PLAN_ACTIVATION_DELAY_OTASP:
877 // Just ignore any changes until the OTASP retry timer kicks in.
878 evaluating_ = false;
879 return;
880 case PLAN_ACTIVATION_INITIATING_ACTIVATION: {
881 switch (network->activation_state()) {
882 case chromeos::ACTIVATION_STATE_ACTIVATED:
883 case chromeos::ACTIVATION_STATE_PARTIALLY_ACTIVATED:
884 new_state = PLAN_ACTIVATION_START;
885 break;
886 case chromeos::ACTIVATION_STATE_NOT_ACTIVATED:
887 case chromeos::ACTIVATION_STATE_ACTIVATING:
888 // Wait in this state until activation state changes.
889 break;
890 default:
891 break;
892 }
893 break;
894 }
895 case PLAN_ACTIVATION_OTASP:
896 case PLAN_ACTIVATION_TRYING_OTASP: {
897 switch (network->activation_state()) {
898 case chromeos::ACTIVATION_STATE_ACTIVATED:
899 if (network->disconnected()) {
900 new_state = GetNextReconnectState(state_);
901 } else if (network->connected()) {
902 if (network->restricted_pool()) {
903 new_state = PLAN_ACTIVATION_PAYMENT_PORTAL_LOADING;
904 } else {
905 new_state = PLAN_ACTIVATION_DONE;
906 }
907 }
908 break;
909 case chromeos::ACTIVATION_STATE_PARTIALLY_ACTIVATED:
910 if (network->connected()) {
911 if (network->restricted_pool())
912 new_state = PLAN_ACTIVATION_PAYMENT_PORTAL_LOADING;
913 } else {
914 new_state = GetNextReconnectState(state_);
915 }
916 break;
917 case chromeos::ACTIVATION_STATE_NOT_ACTIVATED:
918 case chromeos::ACTIVATION_STATE_ACTIVATING:
919 // Wait in this state until activation state changes.
920 break;
921 default:
922 break;
923 }
924 break;
925 }
926 case PLAN_ACTIVATION_RECONNECTING_OTASP_TRY:
927 case PLAN_ACTIVATION_RECONNECTING_PAYMENT:
928 case PLAN_ACTIVATION_RECONNECTING: {
929 if (network->connected()) {
930 // Make sure other networks are not interfering with our detection of
931 // restricted pool.
932 DisableOtherNetworks();
933 // Wait until the service shows up and gets activated.
934 switch (network->activation_state()) {
935 case chromeos::ACTIVATION_STATE_PARTIALLY_ACTIVATED:
936 case chromeos::ACTIVATION_STATE_ACTIVATED:
937 if (network->restricted_pool()) {
938 if (network->error() == chromeos::ERROR_DNS_LOOKUP_FAILED) {
939 LOG(WARNING) << "No connectivity for device "
940 << network->service_path().c_str();
941 // If we are connected but there is no connectivity at all,
942 // restart the whole process again.
943 if (activation_attempt_ < kMaxActivationAttempt) {
944 activation_attempt_++;
945 LOG(WARNING) << "Reconnect attempt #"
946 << activation_attempt_;
947 ForceReconnect(network, kFailedReconnectDelayMS);
948 evaluating_ = false;
949 return;
950 } else {
951 new_state = PLAN_ACTIVATION_ERROR;
952 UMA_HISTOGRAM_COUNTS("Cellular.ActivationRetryFailure", 1);
953 error_description = GetErrorMessage(kFailedConnectivity);
954 }
955 } else {
956 // If we have already received payment, don't show the payment
957 // page again. We should try to reconnect after some
958 // time instead.
959 new_state = PLAN_ACTIVATION_PAYMENT_PORTAL_LOADING;
960 }
961 } else if (network->activation_state() ==
962 chromeos::ACTIVATION_STATE_ACTIVATED) {
963 new_state = PLAN_ACTIVATION_DONE;
964 }
965 break;
966 default:
967 break;
968 }
969 } else if (NeedsReconnecting(network, &new_state, &error_description)) {
970 evaluating_ = false;
971 return;
972 }
973 break;
974 }
975 case PLAN_ACTIVATION_RECONNECTING_OTASP: {
976 if (network->connected()) {
977 // Make sure other networks are not interfering with our detection of
978 // restricted pool.
979 DisableOtherNetworks();
980 // Wait until the service shows up and gets activated.
981 switch (network->activation_state()) {
982 case chromeos::ACTIVATION_STATE_PARTIALLY_ACTIVATED:
983 case chromeos::ACTIVATION_STATE_ACTIVATED:
984 if (network->restricted_pool()) {
985 LOG(WARNING) << "Still no connectivity after OTASP for device "
986 << network->service_path().c_str();
987 // If we have already received payment, don't show the payment
988 // page again. We should try to reconnect after some time instead.
989 if (reconnect_wait_count_ < kMaxReconnectAttemptOTASP) {
990 reconnect_wait_count_++;
991 LOG(WARNING) << "OTASP reconnect attempt #"
992 << reconnect_wait_count_;
993 ForceReconnect(network, kPostPaymentReconnectDelayMS);
994 evaluating_ = false;
995 return;
996 } else {
997 new_state = PLAN_ACTIVATION_ERROR;
998 UMA_HISTOGRAM_COUNTS("Cellular.PostPaymentConnectFailure", 1);
999 error_description = GetErrorMessage(kFailedConnectivity);
1000 }
1001 } else if (network->online()) {
1002 new_state = PLAN_ACTIVATION_DONE;
1003 }
1004 break;
1005 default:
1006 break;
1007 }
1008 } else if (NeedsReconnecting(network, &new_state, &error_description)) {
1009 evaluating_ = false;
1010 return;
1011 }
1012 break;
1013 }
1014 case PLAN_ACTIVATION_PAGE_LOADING:
1015 break;
1016 // Just ignore all signals until the site confirms payment.
1017 case PLAN_ACTIVATION_PAYMENT_PORTAL_LOADING:
1018 case PLAN_ACTIVATION_SHOWING_PAYMENT: {
1019 if (network->disconnected())
1020 new_state = PLAN_ACTIVATION_RECONNECTING_PAYMENT;
1021 break;
1022 }
1023 // Activation completed/failed, ignore network changes.
1024 case PLAN_ACTIVATION_DONE:
1025 case PLAN_ACTIVATION_ERROR:
1026 break;
1027 }
1028
1029 if (new_state != PLAN_ACTIVATION_ERROR &&
1030 GotActivationError(network, &error_description)) {
1031 // Check for this special case when we try to do activate partially
1032 // activated device. If that attempt failed, try to disconnect to clear the
1033 // state and reconnect again.
1034 if ((network->activation_state() ==
1035 chromeos::ACTIVATION_STATE_PARTIALLY_ACTIVATED ||
1036 network->activation_state() == chromeos::ACTIVATION_STATE_ACTIVATING) &&
1037 (network->error() == chromeos::ERROR_NO_ERROR ||
1038 network->error() == chromeos::ERROR_OTASP_FAILED) &&
1039 network->state() == chromeos::STATE_ACTIVATION_FAILURE) {
1040 LOG(WARNING) << "Activation failure detected "
1041 << network->service_path().c_str();
1042 switch (state_) {
1043 case PLAN_ACTIVATION_OTASP:
1044 case PLAN_ACTIVATION_RECONNECTING_OTASP:
1045 new_state = PLAN_ACTIVATION_DELAY_OTASP;
1046 break;
1047 case PLAN_ACTIVATION_TRYING_OTASP:
1048 new_state = PLAN_ACTIVATION_RECONNECTING_OTASP_TRY;
1049 break;
1050 case PLAN_ACTIVATION_INITIATING_ACTIVATION:
1051 new_state = PLAN_ACTIVATION_RECONNECTING;
1052 break;
1053 case PLAN_ACTIVATION_START:
1054 // We are just starting, so this must be previous activation attempt
1055 // failure.
1056 new_state = PLAN_ACTIVATION_TRYING_OTASP;
1057 break;
1058 case PLAN_ACTIVATION_DELAY_OTASP:
1059 case PLAN_ACTIVATION_RECONNECTING_OTASP_TRY:
1060 case PLAN_ACTIVATION_RECONNECTING:
1061 new_state = state_;
1062 break;
1063 default:
1064 new_state = PLAN_ACTIVATION_ERROR;
1065 break;
1066 }
1067 } else {
1068 LOG(WARNING) << "Unexpected activation failure for "
1069 << network->service_path().c_str();
1070 new_state = PLAN_ACTIVATION_ERROR;
1071 }
1072 }
1073
1074 if (new_state == PLAN_ACTIVATION_ERROR && !error_description.length())
1075 error_description = GetErrorMessage(kErrorDefault);
1076
1077 ChangeState(network, new_state, error_description);
1078 evaluating_ = false;
1079 }
1080
1081 MobileSetupHandler::PlanActivationState
1082 MobileSetupHandler::GetNextReconnectState(
1083 MobileSetupHandler::PlanActivationState state) {
1084 switch (state) {
1085 case PLAN_ACTIVATION_INITIATING_ACTIVATION:
1086 return PLAN_ACTIVATION_RECONNECTING;
1087 case PLAN_ACTIVATION_OTASP:
1088 return PLAN_ACTIVATION_RECONNECTING_OTASP;
1089 case PLAN_ACTIVATION_TRYING_OTASP:
1090 return PLAN_ACTIVATION_RECONNECTING_OTASP_TRY;
1091 default:
1092 return PLAN_ACTIVATION_RECONNECTING;
1093 }
1094 }
1095
1096 // Debugging helper function, will take it out at the end.
1097 const char* MobileSetupHandler::GetStateDescription(
1098 PlanActivationState state) {
1099 switch (state) {
1100 case PLAN_ACTIVATION_PAGE_LOADING:
1101 return "PAGE_LOADING";
1102 case PLAN_ACTIVATION_START:
1103 return "ACTIVATION_START";
1104 case PLAN_ACTIVATION_TRYING_OTASP:
1105 return "TRYING_OTASP";
1106 case PLAN_ACTIVATION_RECONNECTING_OTASP_TRY:
1107 return "RECONNECTING_OTASP_TRY";
1108 case PLAN_ACTIVATION_INITIATING_ACTIVATION:
1109 return "INITIATING_ACTIVATION";
1110 case PLAN_ACTIVATION_RECONNECTING:
1111 return "RECONNECTING";
1112 case PLAN_ACTIVATION_PAYMENT_PORTAL_LOADING:
1113 return "PAYMENT_PORTAL_LOADING";
1114 case PLAN_ACTIVATION_SHOWING_PAYMENT:
1115 return "SHOWING_PAYMENT";
1116 case PLAN_ACTIVATION_RECONNECTING_PAYMENT:
1117 return "RECONNECTING_PAYMENT";
1118 case PLAN_ACTIVATION_START_OTASP:
1119 return "START_OTASP";
1120 case PLAN_ACTIVATION_DELAY_OTASP:
1121 return "DELAY_OTASP";
1122 case PLAN_ACTIVATION_OTASP:
1123 return "OTASP";
1124 case PLAN_ACTIVATION_RECONNECTING_OTASP:
1125 return "RECONNECTING_OTASP";
1126 case PLAN_ACTIVATION_DONE:
1127 return "DONE";
1128 case PLAN_ACTIVATION_ERROR:
1129 return "ERROR";
1130 }
1131 return "UNKNOWN";
1132 }
1133
1134
1135 void MobileSetupHandler::CompleteActivation(
1136 chromeos::CellularNetwork* network) {
1137 // Remove observers, we are done with this page.
1138 chromeos::NetworkLibrary* lib = chromeos::CrosLibrary::Get()->
1139 GetNetworkLibrary();
1140 lib->RemoveNetworkManagerObserver(this);
1141 lib->RemoveObserverForAllNetworks(this);
1142 if (lib->IsLocked())
1143 lib->Unlock();
1144 // If we have successfully activated the connection, set autoconnect flag.
1145 if (network)
1146 network->SetAutoConnect(true);
1147 // Reactivate other types of connections if we have
1148 // shut them down previously.
1149 ReEnableOtherConnections();
1150 }
1151
1152 void MobileSetupHandler::UpdatePage(
1153 chromeos::CellularNetwork* network,
1154 const std::string& error_description) {
1155 DictionaryValue device_dict;
1156 if (network)
1157 GetDeviceInfo(network, &device_dict);
1158 device_dict.SetInteger("state", state_);
1159 if (error_description.length())
1160 device_dict.SetString("error", error_description);
1161 web_ui()->CallJavascriptFunction(
1162 kJsDeviceStatusChangedCallback, device_dict);
1163 }
1164
1165
1166 void MobileSetupHandler::ChangeState(chromeos::CellularNetwork* network,
1167 PlanActivationState new_state,
1168 const std::string& error_description) {
1169 static bool first_time = true;
1170 if (state_ == new_state && !first_time)
1171 return;
1172 LOG(WARNING) << "Activation state flip old = "
1173 << GetStateDescription(state_)
1174 << ", new = " << GetStateDescription(new_state);
1175 first_time = false;
1176
1177 // Pick action that should happen on leaving the old state.
1178 switch (state_) {
1179 case PLAN_ACTIVATION_RECONNECTING_OTASP_TRY:
1180 case PLAN_ACTIVATION_RECONNECTING:
1181 case PLAN_ACTIVATION_RECONNECTING_OTASP:
1182 if (reconnect_timer_.IsRunning()) {
1183 reconnect_timer_.Stop();
1184 }
1185 break;
1186 default:
1187 break;
1188 }
1189 state_ = new_state;
1190
1191 // Signal to JS layer that the state is changing.
1192 UpdatePage(network, error_description);
1193
1194 // Pick action that should happen on entering the new state.
1195 switch (new_state) {
1196 case PLAN_ACTIVATION_START:
1197 break;
1198 case PLAN_ACTIVATION_DELAY_OTASP: {
1199 UMA_HISTOGRAM_COUNTS("Cellular.RetryOTASP", 1);
1200 BrowserThread::PostDelayedTask(BrowserThread::UI, FROM_HERE,
1201 base::Bind(&MobileSetupHandler::RetryOTASP, AsWeakPtr()),
1202 base::TimeDelta::FromMilliseconds(kOTASPRetryDelay));
1203 break;
1204 }
1205 case PLAN_ACTIVATION_INITIATING_ACTIVATION:
1206 case PLAN_ACTIVATION_TRYING_OTASP:
1207 case PLAN_ACTIVATION_OTASP:
1208 DCHECK(network);
1209 LOG(WARNING) << "Activating service " << network->service_path().c_str();
1210 UMA_HISTOGRAM_COUNTS("Cellular.ActivationTry", 1);
1211 if (!network->StartActivation()) {
1212 UMA_HISTOGRAM_COUNTS("Cellular.ActivationFailure", 1);
1213 if (new_state == PLAN_ACTIVATION_OTASP) {
1214 ChangeState(network, PLAN_ACTIVATION_DELAY_OTASP, std::string());
1215 } else {
1216 ChangeState(network, PLAN_ACTIVATION_ERROR,
1217 GetErrorMessage(kFailedConnectivity));
1218 }
1219 }
1220 break;
1221 case PLAN_ACTIVATION_RECONNECTING_OTASP_TRY:
1222 case PLAN_ACTIVATION_RECONNECTING:
1223 case PLAN_ACTIVATION_RECONNECTING_PAYMENT:
1224 case PLAN_ACTIVATION_RECONNECTING_OTASP: {
1225 // Start reconnect timer. This will ensure that we are not left in
1226 // limbo by the network library.
1227 if (!reconnect_timer_.IsRunning()) {
1228 reconnect_timer_.Start(
1229 FROM_HERE,
1230 base::TimeDelta::FromMilliseconds(kReconnectTimerDelayMS),
1231 this, &MobileSetupHandler::ReconnectTimerFired);
1232 }
1233 // Reset connection metrics and try to connect.
1234 reconnect_wait_count_ = 0;
1235 connection_retry_count_ = 0;
1236 connection_start_time_ = base::Time::Now();
1237 ConnectToNetwork(network, kReconnectDelayMS);
1238 break;
1239 }
1240 case PLAN_ACTIVATION_PAGE_LOADING:
1241 return;
1242 case PLAN_ACTIVATION_PAYMENT_PORTAL_LOADING:
1243 case PLAN_ACTIVATION_SHOWING_PAYMENT:
1244 // Fix for fix SSL for the walled gardens where cert chain verification
1245 // might not work.
1246 break;
1247 case PLAN_ACTIVATION_DONE:
1248 DCHECK(network);
1249 CompleteActivation(network);
1250 UMA_HISTOGRAM_COUNTS("Cellular.MobileSetupSucceeded", 1);
1251 break;
1252 case PLAN_ACTIVATION_ERROR:
1253 CompleteActivation(NULL);
1254 UMA_HISTOGRAM_COUNTS("Cellular.PlanFailed", 1);
1255 break;
1256 default:
1257 break;
1258 }
1259 }
1260
1261 void MobileSetupHandler::ReEnableOtherConnections() {
1262 chromeos::NetworkLibrary* lib = chromeos::CrosLibrary::Get()->
1263 GetNetworkLibrary();
1264 if (reenable_ethernet_) {
1265 reenable_ethernet_ = false;
1266 lib->EnableEthernetNetworkDevice(true);
1267 }
1268 if (reenable_wifi_) {
1269 reenable_wifi_ = false;
1270 lib->EnableWifiNetworkDevice(true);
1271 }
1272
1273 PrefService* prefs = g_browser_process->local_state();
1274 if (reenable_cert_check_) {
1275 prefs->SetBoolean(prefs::kCertRevocationCheckingEnabled,
1276 true);
1277 reenable_cert_check_ = false;
1278 }
1279 }
1280
1281 void MobileSetupHandler::SetupActivationProcess(
1282 chromeos::CellularNetwork* network) {
1283 if (!network)
1284 return;
1285
1286 // Disable SSL cert checks since we will be doing this in
1287 // restricted pool.
1288 PrefService* prefs = g_browser_process->local_state();
1289 if (!reenable_cert_check_ &&
1290 prefs->GetBoolean(
1291 prefs::kCertRevocationCheckingEnabled)) {
1292 reenable_cert_check_ = true;
1293 prefs->SetBoolean(prefs::kCertRevocationCheckingEnabled, false);
1294 }
1295
1296 chromeos::NetworkLibrary* lib = chromeos::CrosLibrary::Get()->
1297 GetNetworkLibrary();
1298 // Disable autoconnect to cellular network.
1299 network->SetAutoConnect(false);
1300
1301 // Prevent any other network interference.
1302 DisableOtherNetworks();
1303 lib->Lock();
1304 }
1305
1306 void MobileSetupHandler::DisableOtherNetworks() {
1307 chromeos::NetworkLibrary* lib = chromeos::CrosLibrary::Get()->
1308 GetNetworkLibrary();
1309 // Disable ethernet and wifi.
1310 if (lib->ethernet_enabled()) {
1311 reenable_ethernet_ = true;
1312 lib->EnableEthernetNetworkDevice(false);
1313 }
1314 if (lib->wifi_enabled()) {
1315 reenable_wifi_ = true;
1316 lib->EnableWifiNetworkDevice(false);
1317 }
1318 }
1319
1320 bool MobileSetupHandler::GotActivationError(
1321 chromeos::CellularNetwork* network, std::string* error) {
1322 DCHECK(network);
1323 bool got_error = false;
1324 const char* error_code = kErrorDefault;
1325
1326 // This is the magic for detection of errors in during activation process.
1327 if (network->state() == chromeos::STATE_FAILURE &&
1328 network->error() == chromeos::ERROR_AAA_FAILED) {
1329 if (network->activation_state() ==
1330 chromeos::ACTIVATION_STATE_PARTIALLY_ACTIVATED) {
1331 error_code = kErrorBadConnectionPartial;
1332 } else if (network->activation_state() ==
1333 chromeos::ACTIVATION_STATE_ACTIVATED) {
1334 if (network->roaming_state() == chromeos::ROAMING_STATE_HOME) {
1335 error_code = kErrorBadConnectionActivated;
1336 } else if (network->roaming_state() == chromeos::ROAMING_STATE_ROAMING) {
1337 error_code = kErrorRoamingOnConnection;
1338 }
1339 }
1340 got_error = true;
1341 } else if (network->state() == chromeos::STATE_ACTIVATION_FAILURE) {
1342 if (network->error() == chromeos::ERROR_NEED_EVDO) {
1343 if (network->activation_state() ==
1344 chromeos::ACTIVATION_STATE_PARTIALLY_ACTIVATED)
1345 error_code = kErrorNoEVDO;
1346 } else if (network->error() == chromeos::ERROR_NEED_HOME_NETWORK) {
1347 if (network->activation_state() ==
1348 chromeos::ACTIVATION_STATE_NOT_ACTIVATED) {
1349 error_code = kErrorRoamingActivation;
1350 } else if (network->activation_state() ==
1351 chromeos::ACTIVATION_STATE_PARTIALLY_ACTIVATED) {
1352 error_code = kErrorRoamingPartiallyActivated;
1353 }
1354 }
1355 got_error = true;
1356 }
1357
1358 if (got_error)
1359 *error = GetErrorMessage(error_code);
1360
1361 return got_error;
1362 }
1363
1364 void MobileSetupHandler::GetDeviceInfo(chromeos::CellularNetwork* network,
1365 DictionaryValue* value) { 309 DictionaryValue* value) {
1366 DCHECK(network); 310 DCHECK(network);
1367 chromeos::NetworkLibrary* cros = 311 chromeos::NetworkLibrary* cros =
1368 chromeos::CrosLibrary::Get()->GetNetworkLibrary(); 312 chromeos::CrosLibrary::Get()->GetNetworkLibrary();
1369 if (!cros) 313 if (!cros)
1370 return; 314 return;
1371 value->SetString("carrier", network->name()); 315 value->SetString("carrier", network->name());
1372 value->SetString("payment_url", network->payment_url()); 316 value->SetString("payment_url", network->payment_url());
1373 if (network->using_post() && network->post_data().length()) 317 if (network->using_post() && network->post_data().length())
1374 value->SetString("post_data", network->post_data()); 318 value->SetString("post_data", network->post_data());
1375 319
1376 const chromeos::NetworkDevice* device = 320 const chromeos::NetworkDevice* device =
1377 cros->FindNetworkDeviceByPath(network->device_path()); 321 cros->FindNetworkDeviceByPath(network->device_path());
1378 if (device) { 322 if (device) {
1379 value->SetString("MEID", device->meid()); 323 value->SetString("MEID", device->meid());
1380 value->SetString("IMEI", device->imei()); 324 value->SetString("IMEI", device->imei());
1381 value->SetString("MDN", device->mdn()); 325 value->SetString("MDN", device->mdn());
1382 } 326 }
1383 } 327 }
1384 328
1385 std::string MobileSetupHandler::GetErrorMessage(const std::string& code) {
1386 return cellular_config_->GetErrorMessage(code);
1387 }
1388
1389 void MobileSetupHandler::StartActivationOnUIThread() {
1390 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1391 chromeos::CellularNetwork* network = GetCellularNetwork(service_path_);
1392 if (!network || !network->SupportsActivation())
1393 return;
1394
1395 if (!chromeos::CrosLibrary::Get()->GetNetworkLibrary()->IsLocked())
1396 SetupActivationProcess(network);
1397 else
1398 already_running_ = true;
1399
1400 StartActivation();
1401 }
1402
1403 //////////////////////////////////////////////////////////////////////////////// 329 ////////////////////////////////////////////////////////////////////////////////
1404 // 330 //
1405 // MobileSetupUI 331 // MobileSetupUI
1406 // 332 //
1407 //////////////////////////////////////////////////////////////////////////////// 333 ////////////////////////////////////////////////////////////////////////////////
1408 334
1409 MobileSetupUI::MobileSetupUI(content::WebUI* web_ui) 335 MobileSetupUI::MobileSetupUI(content::WebUI* web_ui)
1410 : WebUIController(web_ui) { 336 : WebUIController(web_ui) {
1411 chromeos::CellularNetwork* network = GetCellularNetwork(); 337 web_ui->AddMessageHandler(new MobileSetupHandler());
1412 std::string service_path = network ? network->service_path() : std::string(); 338 MobileSetupUIHTMLSource* html_source = new MobileSetupUIHTMLSource();
1413 web_ui->AddMessageHandler(new MobileSetupHandler(service_path));
1414 MobileSetupUIHTMLSource* html_source =
1415 new MobileSetupUIHTMLSource(service_path);
1416 339
1417 // Set up the chrome://mobilesetup/ source. 340 // Set up the chrome://mobilesetup/ source.
1418 Profile* profile = Profile::FromWebUI(web_ui); 341 Profile* profile = Profile::FromWebUI(web_ui);
1419 ChromeURLDataManager::AddDataSource(profile, html_source); 342 ChromeURLDataManager::AddDataSource(profile, html_source);
1420 } 343 }
1421 344
1422 void MobileSetupUI::RenderViewCreated(RenderViewHost* host) { 345 void MobileSetupUI::RenderViewCreated(RenderViewHost* host) {
1423 // Destroyed by the corresponding RenderViewHost 346 // Destroyed by the corresponding RenderViewHost
1424 new PortalFrameLoadObserver(AsWeakPtr(), host); 347 new PortalFrameLoadObserver(AsWeakPtr(), host);
1425 } 348 }
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698