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.
5 #include "chrome/browser/chromeos/settings/device_settings_service.h"
8 #include "base/logging.h"
9 #include "base/message_loop/message_loop.h"
10 #include "base/stl_util.h"
11 #include "base/time/time.h"
12 #include "chrome/browser/chrome_notification_types.h"
13 #include "chrome/browser/chromeos/ownership/owner_settings_service_chromeos.h"
14 #include "chrome/browser/chromeos/policy/proto/chrome_device_policy.pb.h"
15 #include "chrome/browser/chromeos/settings/session_manager_operation.h"
16 #include "components/ownership/owner_key_util.h"
17 #include "components/policy/core/common/cloud/cloud_policy_constants.h"
18 #include "content/public/browser/browser_thread.h"
19 #include "content/public/browser/notification_service.h"
20 #include "content/public/browser/notification_source.h"
21 #include "crypto/rsa_private_key.h"
23 namespace em = enterprise_management;
25 using ownership::OwnerKeyUtil;
26 using ownership::PublicKey;
30 // Delay between load retries when there was a validation error.
31 // NOTE: This code is here to mitigate clock loss on some devices where policy
32 // loads will fail with a validation error caused by RTC clock being reset when
33 // the battery is drained.
34 int kLoadRetryDelayMs = 1000 * 5;
35 // Maximal number of retries before we give up. Calculated to allow for 10 min
37 int kMaxLoadRetries = (1000 * 60 * 10) / kLoadRetryDelayMs;
39 // Returns true if it is okay to transfer from the current mode to the new
40 // mode. This function should be called in SetManagementMode().
41 bool CheckManagementModeTransition(em::PolicyData::ManagementMode current_mode,
42 em::PolicyData::ManagementMode new_mode) {
43 // Mode is not changed.
44 if (current_mode == new_mode)
47 switch (current_mode) {
48 case em::PolicyData::NOT_MANAGED:
49 // For consumer management enrollment.
50 return new_mode == em::PolicyData::CONSUMER_MANAGED;
52 case em::PolicyData::ENTERPRISE_MANAGED:
53 // Management mode cannot be set when it is currently ENTERPRISE_MANAGED.
56 case em::PolicyData::CONSUMER_MANAGED:
57 // For consumer management unenrollment.
58 return new_mode == em::PolicyData::NOT_MANAGED;
69 DeviceSettingsService::Observer::~Observer() {}
71 static DeviceSettingsService* g_device_settings_service = NULL;
74 void DeviceSettingsService::Initialize() {
75 CHECK(!g_device_settings_service);
76 g_device_settings_service = new DeviceSettingsService();
80 bool DeviceSettingsService::IsInitialized() {
81 return g_device_settings_service;
85 void DeviceSettingsService::Shutdown() {
86 DCHECK(g_device_settings_service);
87 delete g_device_settings_service;
88 g_device_settings_service = NULL;
92 DeviceSettingsService* DeviceSettingsService::Get() {
93 CHECK(g_device_settings_service);
94 return g_device_settings_service;
97 DeviceSettingsService::DeviceSettingsService()
98 : session_manager_client_(NULL),
99 store_status_(STORE_SUCCESS),
100 load_retries_left_(kMaxLoadRetries),
101 weak_factory_(this) {
104 DeviceSettingsService::~DeviceSettingsService() {
105 DCHECK(pending_operations_.empty());
106 FOR_EACH_OBSERVER(Observer, observers_, OnDeviceSettingsServiceShutdown());
109 void DeviceSettingsService::SetSessionManager(
110 SessionManagerClient* session_manager_client,
111 scoped_refptr<OwnerKeyUtil> owner_key_util) {
112 DCHECK(session_manager_client);
113 DCHECK(owner_key_util.get());
114 DCHECK(!session_manager_client_);
115 DCHECK(!owner_key_util_.get());
117 session_manager_client_ = session_manager_client;
118 owner_key_util_ = owner_key_util;
120 session_manager_client_->AddObserver(this);
122 StartNextOperation();
125 void DeviceSettingsService::UnsetSessionManager() {
126 pending_operations_.clear();
128 if (session_manager_client_)
129 session_manager_client_->RemoveObserver(this);
130 session_manager_client_ = NULL;
131 owner_key_util_ = NULL;
134 scoped_refptr<PublicKey> DeviceSettingsService::GetPublicKey() {
138 void DeviceSettingsService::Load() {
142 void DeviceSettingsService::SignAndStore(
143 scoped_ptr<em::ChromeDeviceSettingsProto> new_settings,
144 const base::Closure& callback) {
145 scoped_ptr<em::PolicyData> policy =
146 OwnerSettingsServiceChromeOS::AssemblePolicy(
147 GetUsername(), policy_data(), new_settings.get());
148 EnqueueSignAndStore(policy.Pass(), callback);
151 void DeviceSettingsService::SetManagementSettings(
152 em::PolicyData::ManagementMode management_mode,
153 const std::string& request_token,
154 const std::string& device_id,
155 const base::Closure& callback) {
156 if (!owner_settings_service_) {
157 HandleError(STORE_KEY_UNAVAILABLE, callback);
161 em::PolicyData::ManagementMode current_mode = em::PolicyData::NOT_MANAGED;
162 if (policy_data() && policy_data()->has_management_mode())
163 current_mode = policy_data()->management_mode();
165 if (!CheckManagementModeTransition(current_mode, management_mode)) {
166 LOG(ERROR) << "Invalid management mode transition: current mode = "
167 << current_mode << ", new mode = " << management_mode;
168 HandleError(DeviceSettingsService::STORE_POLICY_ERROR, callback);
172 scoped_ptr<em::PolicyData> policy =
173 OwnerSettingsServiceChromeOS::AssemblePolicy(
174 GetUsername(), policy_data(), device_settings());
176 HandleError(DeviceSettingsService::STORE_POLICY_ERROR, callback);
180 policy->set_management_mode(management_mode);
181 policy->set_request_token(request_token);
182 policy->set_device_id(device_id);
184 EnqueueSignAndStore(policy.Pass(), callback);
187 void DeviceSettingsService::Store(scoped_ptr<em::PolicyFetchResponse> policy,
188 const base::Closure& callback) {
189 Enqueue(linked_ptr<SessionManagerOperation>(new StoreSettingsOperation(
190 base::Bind(&DeviceSettingsService::HandleCompletedOperation,
191 weak_factory_.GetWeakPtr(),
196 DeviceSettingsService::OwnershipStatus
197 DeviceSettingsService::GetOwnershipStatus() {
198 if (public_key_.get())
199 return public_key_->is_loaded() ? OWNERSHIP_TAKEN : OWNERSHIP_NONE;
200 return OWNERSHIP_UNKNOWN;
203 void DeviceSettingsService::GetOwnershipStatusAsync(
204 const OwnershipStatusCallback& callback) {
205 if (public_key_.get()) {
206 // If there is a key, report status immediately.
207 base::MessageLoop::current()->PostTask(
208 FROM_HERE, base::Bind(callback, GetOwnershipStatus()));
210 // If the key hasn't been loaded yet, enqueue the callback to be fired when
211 // the next SessionManagerOperation completes. If no operation is pending,
212 // start a load operation to fetch the key and report the result.
213 pending_ownership_status_callbacks_.push_back(callback);
214 if (pending_operations_.empty())
219 bool DeviceSettingsService::HasPrivateOwnerKey() {
220 return owner_settings_service_ && owner_settings_service_->IsOwner();
223 void DeviceSettingsService::InitOwner(
224 const std::string& username,
225 const base::WeakPtr<ownership::OwnerSettingsService>&
226 owner_settings_service) {
227 // When InitOwner() is called twice with the same |username| it's
228 // worth to reload settings since owner key may become available.
229 if (!username_.empty() && username_ != username)
231 username_ = username;
232 owner_settings_service_ = owner_settings_service;
237 const std::string& DeviceSettingsService::GetUsername() const {
241 ownership::OwnerSettingsService*
242 DeviceSettingsService::GetOwnerSettingsService() const {
243 return owner_settings_service_.get();
246 void DeviceSettingsService::AddObserver(Observer* observer) {
247 observers_.AddObserver(observer);
250 void DeviceSettingsService::RemoveObserver(Observer* observer) {
251 observers_.RemoveObserver(observer);
254 void DeviceSettingsService::OwnerKeySet(bool success) {
256 LOG(ERROR) << "Owner key change failed.";
264 void DeviceSettingsService::PropertyChangeComplete(bool success) {
266 LOG(ERROR) << "Policy update failed.";
273 void DeviceSettingsService::Enqueue(
274 const linked_ptr<SessionManagerOperation>& operation) {
275 pending_operations_.push_back(operation);
276 if (pending_operations_.front().get() == operation.get())
277 StartNextOperation();
280 void DeviceSettingsService::EnqueueLoad(bool force_key_load) {
281 linked_ptr<SessionManagerOperation> operation(new LoadSettingsOperation(
282 base::Bind(&DeviceSettingsService::HandleCompletedOperation,
283 weak_factory_.GetWeakPtr(),
285 operation->set_force_key_load(force_key_load);
286 operation->set_username(username_);
287 operation->set_owner_settings_service(owner_settings_service_);
291 void DeviceSettingsService::EnqueueSignAndStore(
292 scoped_ptr<enterprise_management::PolicyData> policy,
293 const base::Closure& callback) {
294 linked_ptr<SessionManagerOperation> operation(
295 new SignAndStoreSettingsOperation(
296 base::Bind(&DeviceSettingsService::HandleCompletedOperation,
297 weak_factory_.GetWeakPtr(),
300 operation->set_owner_settings_service(owner_settings_service_);
304 void DeviceSettingsService::EnsureReload(bool force_key_load) {
305 if (!pending_operations_.empty()) {
306 pending_operations_.front()->set_username(username_);
307 pending_operations_.front()->set_owner_settings_service(
308 owner_settings_service_);
309 pending_operations_.front()->RestartLoad(force_key_load);
311 EnqueueLoad(force_key_load);
315 void DeviceSettingsService::StartNextOperation() {
316 if (!pending_operations_.empty() && session_manager_client_ &&
317 owner_key_util_.get()) {
318 pending_operations_.front()->Start(
319 session_manager_client_, owner_key_util_, public_key_);
323 void DeviceSettingsService::HandleCompletedOperation(
324 const base::Closure& callback,
325 SessionManagerOperation* operation,
327 DCHECK_EQ(operation, pending_operations_.front().get());
328 store_status_ = status;
330 OwnershipStatus ownership_status = OWNERSHIP_UNKNOWN;
331 scoped_refptr<PublicKey> new_key(operation->public_key());
333 ownership_status = new_key->is_loaded() ? OWNERSHIP_TAKEN : OWNERSHIP_NONE;
335 NOTREACHED() << "Failed to determine key status.";
338 bool new_owner_key = false;
339 if (public_key_.get() != new_key.get()) {
340 public_key_ = new_key;
341 new_owner_key = true;
344 if (status == STORE_SUCCESS) {
345 policy_data_ = operation->policy_data().Pass();
346 device_settings_ = operation->device_settings().Pass();
347 load_retries_left_ = kMaxLoadRetries;
348 } else if (status != STORE_KEY_UNAVAILABLE) {
349 LOG(ERROR) << "Session manager operation failed: " << status;
350 // Validation errors can be temporary if the rtc has gone on holiday for a
351 // short while. So we will retry such loads for up to 10 minutes.
352 if (status == STORE_TEMP_VALIDATION_ERROR) {
353 if (load_retries_left_ > 0) {
354 load_retries_left_--;
355 LOG(ERROR) << "A re-load has been scheduled due to a validation error.";
356 content::BrowserThread::PostDelayedTask(
357 content::BrowserThread::UI,
359 base::Bind(&DeviceSettingsService::Load, base::Unretained(this)),
360 base::TimeDelta::FromMilliseconds(kLoadRetryDelayMs));
362 // Once we've given up retrying, the validation error is not temporary
364 store_status_ = STORE_VALIDATION_ERROR;
370 FOR_EACH_OBSERVER(Observer, observers_, OwnershipStatusChanged());
371 content::NotificationService::current()->Notify(
372 chrome::NOTIFICATION_OWNERSHIP_STATUS_CHANGED,
373 content::Source<DeviceSettingsService>(this),
374 content::NotificationService::NoDetails());
377 FOR_EACH_OBSERVER(Observer, observers_, DeviceSettingsUpdated());
379 std::vector<OwnershipStatusCallback> callbacks;
380 callbacks.swap(pending_ownership_status_callbacks_);
381 for (std::vector<OwnershipStatusCallback>::iterator iter(callbacks.begin());
382 iter != callbacks.end(); ++iter) {
383 iter->Run(ownership_status);
386 // The completion callback happens after the notification so clients can
387 // filter self-triggered updates.
388 if (!callback.is_null())
391 // Only remove the pending operation here, so new operations triggered by any
392 // of the callbacks above are queued up properly.
393 pending_operations_.pop_front();
395 StartNextOperation();
398 void DeviceSettingsService::HandleError(Status status,
399 const base::Closure& callback) {
400 store_status_ = status;
402 LOG(ERROR) << "Session manager operation failed: " << status;
404 FOR_EACH_OBSERVER(Observer, observers_, DeviceSettingsUpdated());
406 // The completion callback happens after the notification so clients can
407 // filter self-triggered updates.
408 if (!callback.is_null())
412 ScopedTestDeviceSettingsService::ScopedTestDeviceSettingsService() {
413 DeviceSettingsService::Initialize();
416 ScopedTestDeviceSettingsService::~ScopedTestDeviceSettingsService() {
417 // Clean pending operations.
418 DeviceSettingsService::Get()->UnsetSessionManager();
419 DeviceSettingsService::Shutdown();
422 } // namespace chromeos