base::Time multiplicative operator overloading
[chromium-blink-merge.git] / chrome / browser / signin / easy_unlock_service_signin_chromeos.cc
blob4fd94240095d84f57b2d6fa69e0a6335fda6d500
1 // Copyright 2014 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.
5 #include "chrome/browser/signin/easy_unlock_service_signin_chromeos.h"
7 #include "base/basictypes.h"
8 #include "base/bind.h"
9 #include "base/location.h"
10 #include "base/logging.h"
11 #include "base/stl_util.h"
12 #include "base/sys_info.h"
13 #include "base/thread_task_runner_handle.h"
14 #include "base/time/time.h"
15 #include "chrome/browser/chromeos/login/easy_unlock/easy_unlock_key_manager.h"
16 #include "chrome/browser/chromeos/login/session/user_session_manager.h"
17 #include "chrome/browser/signin/easy_unlock_app_manager.h"
18 #include "chrome/browser/signin/easy_unlock_metrics.h"
19 #include "chromeos/login/auth/user_context.h"
20 #include "chromeos/tpm/tpm_token_loader.h"
22 namespace {
24 // The maximum allowed backoff interval when waiting for cryptohome to start.
25 uint32 kMaxCryptohomeBackoffIntervalMs = 10000u;
27 // If the data load fails, the initial interval after which the load will be
28 // retried. Further intervals will exponentially increas by factor 2.
29 uint32 kInitialCryptohomeBackoffIntervalMs = 200u;
31 // Calculates the backoff interval that should be used next.
32 // |backoff| The last backoff interval used.
33 uint32 GetNextBackoffInterval(uint32 backoff) {
34 if (backoff == 0u)
35 return kInitialCryptohomeBackoffIntervalMs;
36 return backoff * 2;
39 void LoadDataForUser(
40 const std::string& user_id,
41 uint32 backoff_ms,
42 const chromeos::EasyUnlockKeyManager::GetDeviceDataListCallback& callback);
44 // Callback passed to |LoadDataForUser()|.
45 // If |LoadDataForUser| function succeeded, it invokes |callback| with the
46 // results.
47 // If |LoadDataForUser| failed and further retries are allowed, schedules new
48 // |LoadDataForUser| call with some backoff. If no further retires are allowed,
49 // it invokes |callback| with the |LoadDataForUser| results.
50 void RetryDataLoadOnError(
51 const std::string& user_id,
52 uint32 backoff_ms,
53 const chromeos::EasyUnlockKeyManager::GetDeviceDataListCallback& callback,
54 bool success,
55 const chromeos::EasyUnlockDeviceKeyDataList& data_list) {
56 if (success) {
57 callback.Run(success, data_list);
58 return;
61 uint32 next_backoff_ms = GetNextBackoffInterval(backoff_ms);
62 if (next_backoff_ms > kMaxCryptohomeBackoffIntervalMs) {
63 callback.Run(false, data_list);
64 return;
67 base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
68 FROM_HERE,
69 base::Bind(&LoadDataForUser, user_id, next_backoff_ms, callback),
70 base::TimeDelta::FromMilliseconds(next_backoff_ms));
73 // Loads device data list associated with the user's Easy unlock keys.
74 void LoadDataForUser(
75 const std::string& user_id,
76 uint32 backoff_ms,
77 const chromeos::EasyUnlockKeyManager::GetDeviceDataListCallback& callback) {
78 chromeos::EasyUnlockKeyManager* key_manager =
79 chromeos::UserSessionManager::GetInstance()->GetEasyUnlockKeyManager();
80 DCHECK(key_manager);
82 key_manager->GetDeviceDataList(
83 chromeos::UserContext(user_id),
84 base::Bind(&RetryDataLoadOnError, user_id, backoff_ms, callback));
87 } // namespace
89 EasyUnlockServiceSignin::UserData::UserData()
90 : state(EasyUnlockServiceSignin::USER_DATA_STATE_INITIAL) {
93 EasyUnlockServiceSignin::UserData::~UserData() {}
95 EasyUnlockServiceSignin::EasyUnlockServiceSignin(Profile* profile)
96 : EasyUnlockService(profile),
97 allow_cryptohome_backoff_(true),
98 service_active_(false),
99 weak_ptr_factory_(this) {
102 EasyUnlockServiceSignin::~EasyUnlockServiceSignin() {
105 EasyUnlockService::Type EasyUnlockServiceSignin::GetType() const {
106 return EasyUnlockService::TYPE_SIGNIN;
109 std::string EasyUnlockServiceSignin::GetUserEmail() const {
110 return user_id_;
113 void EasyUnlockServiceSignin::LaunchSetup() {
114 NOTREACHED();
117 const base::DictionaryValue* EasyUnlockServiceSignin::GetPermitAccess() const {
118 return NULL;
121 void EasyUnlockServiceSignin::SetPermitAccess(
122 const base::DictionaryValue& permit) {
123 NOTREACHED();
126 void EasyUnlockServiceSignin::ClearPermitAccess() {
127 NOTREACHED();
130 const base::ListValue* EasyUnlockServiceSignin::GetRemoteDevices() const {
131 const UserData* data = FindLoadedDataForCurrentUser();
132 if (!data)
133 return NULL;
134 return &data->remote_devices_value;
137 void EasyUnlockServiceSignin::SetRemoteDevices(
138 const base::ListValue& devices) {
139 NOTREACHED();
142 void EasyUnlockServiceSignin::RunTurnOffFlow() {
143 NOTREACHED();
146 void EasyUnlockServiceSignin::ResetTurnOffFlow() {
147 NOTREACHED();
150 EasyUnlockService::TurnOffFlowStatus
151 EasyUnlockServiceSignin::GetTurnOffFlowStatus() const {
152 return EasyUnlockService::IDLE;
155 std::string EasyUnlockServiceSignin::GetChallenge() const {
156 const UserData* data = FindLoadedDataForCurrentUser();
157 // TODO(xiyuan): Use correct remote device instead of hard coded first one.
158 uint32 device_index = 0;
159 if (!data || data->devices.size() <= device_index)
160 return std::string();
161 return data->devices[device_index].challenge;
164 std::string EasyUnlockServiceSignin::GetWrappedSecret() const {
165 const UserData* data = FindLoadedDataForCurrentUser();
166 // TODO(xiyuan): Use correct remote device instead of hard coded first one.
167 uint32 device_index = 0;
168 if (!data || data->devices.size() <= device_index)
169 return std::string();
170 return data->devices[device_index].wrapped_secret;
173 void EasyUnlockServiceSignin::RecordEasySignInOutcome(
174 const std::string& user_id,
175 bool success) const {
176 DCHECK_EQ(GetUserEmail(), user_id);
178 RecordEasyUnlockSigninEvent(
179 success ? EASY_UNLOCK_SUCCESS : EASY_UNLOCK_FAILURE);
180 DVLOG(1) << "Easy sign-in " << (success ? "success" : "failure");
183 void EasyUnlockServiceSignin::RecordPasswordLoginEvent(
184 const std::string& user_id) const {
185 // This happens during tests, where a user could log in without the user pod
186 // being focused.
187 if (GetUserEmail() != user_id)
188 return;
190 if (!IsEnabled())
191 return;
193 EasyUnlockAuthEvent event = GetPasswordAuthEvent();
194 RecordEasyUnlockSigninEvent(event);
195 DVLOG(1) << "Easy Sign-in password login event, event=" << event;
198 void EasyUnlockServiceSignin::StartAutoPairing(
199 const AutoPairingResultCallback& callback) {
200 NOTREACHED();
203 void EasyUnlockServiceSignin::SetAutoPairingResult(
204 bool success,
205 const std::string& error) {
206 NOTREACHED();
209 void EasyUnlockServiceSignin::InitializeInternal() {
210 if (chromeos::LoginState::Get()->IsUserLoggedIn())
211 return;
213 service_active_ = true;
215 chromeos::LoginState::Get()->AddObserver(this);
216 ScreenlockBridge* screenlock_bridge = ScreenlockBridge::Get();
217 screenlock_bridge->AddObserver(this);
218 if (!screenlock_bridge->focused_user_id().empty())
219 OnFocusedUserChanged(screenlock_bridge->focused_user_id());
222 void EasyUnlockServiceSignin::ShutdownInternal() {
223 if (!service_active_)
224 return;
225 service_active_ = false;
227 weak_ptr_factory_.InvalidateWeakPtrs();
228 ScreenlockBridge::Get()->RemoveObserver(this);
229 chromeos::LoginState::Get()->RemoveObserver(this);
230 STLDeleteContainerPairSecondPointers(user_data_.begin(), user_data_.end());
231 user_data_.clear();
234 bool EasyUnlockServiceSignin::IsAllowedInternal() const {
235 return service_active_ &&
236 !user_id_.empty() &&
237 !chromeos::LoginState::Get()->IsUserLoggedIn();
240 void EasyUnlockServiceSignin::OnWillFinalizeUnlock(bool success) {
241 // This code path should only be exercised for the lock screen, not for the
242 // sign-in screen.
243 NOTREACHED();
246 void EasyUnlockServiceSignin::OnScreenDidLock(
247 ScreenlockBridge::LockHandler::ScreenType screen_type) {
248 // In production code, the screen type should always be the signin screen; but
249 // in tests, the screen type might be different.
250 if (screen_type != ScreenlockBridge::LockHandler::SIGNIN_SCREEN)
251 return;
253 // Update initial UI is when the account picker on login screen is ready.
254 ShowInitialUserState();
257 void EasyUnlockServiceSignin::OnScreenDidUnlock(
258 ScreenlockBridge::LockHandler::ScreenType screen_type) {
259 // In production code, the screen type should always be the signin screen; but
260 // in tests, the screen type might be different.
261 if (screen_type != ScreenlockBridge::LockHandler::SIGNIN_SCREEN)
262 return;
264 DisableAppWithoutResettingScreenlockState();
266 Shutdown();
269 void EasyUnlockServiceSignin::OnFocusedUserChanged(const std::string& user_id) {
270 if (user_id_ == user_id)
271 return;
273 // Setting or clearing the user_id may changed |IsAllowed| value, so in these
274 // cases update the app state. Otherwise, it's enough to notify the app the
275 // user data has been updated.
276 bool should_update_app_state = user_id_.empty() != user_id.empty();
277 user_id_ = user_id;
279 ResetScreenlockState();
280 ShowInitialUserState();
282 if (should_update_app_state) {
283 UpdateAppState();
284 } else {
285 NotifyUserUpdated();
288 LoadCurrentUserDataIfNeeded();
290 // Start loading TPM system token.
291 // The system token will be needed to sign a nonce using TPM private key
292 // during the sign-in protocol.
293 EasyUnlockScreenlockStateHandler::HardlockState hardlock_state;
294 if (GetPersistedHardlockState(&hardlock_state) &&
295 hardlock_state != EasyUnlockScreenlockStateHandler::NO_PAIRING) {
296 chromeos::TPMTokenLoader::Get()->EnsureStarted();
300 void EasyUnlockServiceSignin::LoggedInStateChanged() {
301 if (!chromeos::LoginState::Get()->IsUserLoggedIn())
302 return;
303 DisableAppWithoutResettingScreenlockState();
306 void EasyUnlockServiceSignin::LoadCurrentUserDataIfNeeded() {
307 // TODO(xiyuan): Revisit this when adding tests.
308 if (!base::SysInfo::IsRunningOnChromeOS())
309 return;
311 if (user_id_.empty() || !service_active_)
312 return;
314 std::map<std::string, UserData*>::iterator it = user_data_.find(user_id_);
315 if (it == user_data_.end())
316 user_data_.insert(std::make_pair(user_id_, new UserData()));
318 UserData* data = user_data_[user_id_];
320 if (data->state != USER_DATA_STATE_INITIAL)
321 return;
322 data->state = USER_DATA_STATE_LOADING;
324 LoadDataForUser(
325 user_id_,
326 allow_cryptohome_backoff_ ? 0u : kMaxCryptohomeBackoffIntervalMs,
327 base::Bind(&EasyUnlockServiceSignin::OnUserDataLoaded,
328 weak_ptr_factory_.GetWeakPtr(),
329 user_id_));
332 void EasyUnlockServiceSignin::OnUserDataLoaded(
333 const std::string& user_id,
334 bool success,
335 const chromeos::EasyUnlockDeviceKeyDataList& devices) {
336 allow_cryptohome_backoff_ = false;
338 UserData* data = user_data_[user_id_];
339 data->state = USER_DATA_STATE_LOADED;
340 if (success) {
341 data->devices = devices;
342 chromeos::EasyUnlockKeyManager::DeviceDataListToRemoteDeviceList(
343 user_id, devices, &data->remote_devices_value);
346 // If the fetched data belongs to the currently focused user, notify the app
347 // that it has to refresh it's user data.
348 if (user_id == user_id_)
349 NotifyUserUpdated();
352 const EasyUnlockServiceSignin::UserData*
353 EasyUnlockServiceSignin::FindLoadedDataForCurrentUser() const {
354 if (user_id_.empty())
355 return NULL;
357 std::map<std::string, UserData*>::const_iterator it =
358 user_data_.find(user_id_);
359 if (it == user_data_.end())
360 return NULL;
361 if (it->second->state != USER_DATA_STATE_LOADED)
362 return NULL;
363 return it->second;