Switch global error menu icon to vectorized MD asset
[chromium-blink-merge.git] / chrome / browser / chromeos / settings / device_settings_service.cc
bloba696102cd0e141a4895e8c62e05c39a66dea12b3
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"
7 #include "base/bind.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;
28 namespace {
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
36 // of retry time.
37 int kMaxLoadRetries = (1000 * 60 * 10) / kLoadRetryDelayMs;
39 } // namespace
41 namespace chromeos {
43 DeviceSettingsService::Observer::~Observer() {}
45 static DeviceSettingsService* g_device_settings_service = NULL;
47 // static
48 void DeviceSettingsService::Initialize() {
49 CHECK(!g_device_settings_service);
50 g_device_settings_service = new DeviceSettingsService();
53 // static
54 bool DeviceSettingsService::IsInitialized() {
55 return g_device_settings_service;
58 // static
59 void DeviceSettingsService::Shutdown() {
60 DCHECK(g_device_settings_service);
61 delete g_device_settings_service;
62 g_device_settings_service = NULL;
65 // static
66 DeviceSettingsService* DeviceSettingsService::Get() {
67 CHECK(g_device_settings_service);
68 return g_device_settings_service;
71 DeviceSettingsService::DeviceSettingsService()
72 : session_manager_client_(NULL),
73 store_status_(STORE_SUCCESS),
74 load_retries_left_(kMaxLoadRetries),
75 weak_factory_(this) {
78 DeviceSettingsService::~DeviceSettingsService() {
79 DCHECK(pending_operations_.empty());
80 FOR_EACH_OBSERVER(Observer, observers_, OnDeviceSettingsServiceShutdown());
83 void DeviceSettingsService::SetSessionManager(
84 SessionManagerClient* session_manager_client,
85 scoped_refptr<OwnerKeyUtil> owner_key_util) {
86 DCHECK(session_manager_client);
87 DCHECK(owner_key_util.get());
88 DCHECK(!session_manager_client_);
89 DCHECK(!owner_key_util_.get());
91 session_manager_client_ = session_manager_client;
92 owner_key_util_ = owner_key_util;
94 session_manager_client_->AddObserver(this);
96 StartNextOperation();
99 void DeviceSettingsService::UnsetSessionManager() {
100 pending_operations_.clear();
102 if (session_manager_client_)
103 session_manager_client_->RemoveObserver(this);
104 session_manager_client_ = NULL;
105 owner_key_util_ = NULL;
108 scoped_refptr<PublicKey> DeviceSettingsService::GetPublicKey() {
109 return public_key_;
112 void DeviceSettingsService::Load() {
113 EnqueueLoad(false);
116 void DeviceSettingsService::Store(scoped_ptr<em::PolicyFetchResponse> policy,
117 const base::Closure& callback) {
118 Enqueue(linked_ptr<SessionManagerOperation>(new StoreSettingsOperation(
119 base::Bind(&DeviceSettingsService::HandleCompletedOperation,
120 weak_factory_.GetWeakPtr(),
121 callback),
122 policy.Pass())));
125 DeviceSettingsService::OwnershipStatus
126 DeviceSettingsService::GetOwnershipStatus() {
127 if (public_key_.get())
128 return public_key_->is_loaded() ? OWNERSHIP_TAKEN : OWNERSHIP_NONE;
129 return OWNERSHIP_UNKNOWN;
132 void DeviceSettingsService::GetOwnershipStatusAsync(
133 const OwnershipStatusCallback& callback) {
134 if (public_key_.get()) {
135 // If there is a key, report status immediately.
136 base::MessageLoop::current()->PostTask(
137 FROM_HERE, base::Bind(callback, GetOwnershipStatus()));
138 } else {
139 // If the key hasn't been loaded yet, enqueue the callback to be fired when
140 // the next SessionManagerOperation completes. If no operation is pending,
141 // start a load operation to fetch the key and report the result.
142 pending_ownership_status_callbacks_.push_back(callback);
143 if (pending_operations_.empty())
144 EnqueueLoad(false);
148 bool DeviceSettingsService::HasPrivateOwnerKey() {
149 return owner_settings_service_ && owner_settings_service_->IsOwner();
152 void DeviceSettingsService::InitOwner(
153 const std::string& username,
154 const base::WeakPtr<ownership::OwnerSettingsService>&
155 owner_settings_service) {
156 // When InitOwner() is called twice with the same |username| it's
157 // worth to reload settings since owner key may become available.
158 if (!username_.empty() && username_ != username)
159 return;
160 username_ = username;
161 owner_settings_service_ = owner_settings_service;
163 EnsureReload(true);
166 const std::string& DeviceSettingsService::GetUsername() const {
167 return username_;
170 ownership::OwnerSettingsService*
171 DeviceSettingsService::GetOwnerSettingsService() const {
172 return owner_settings_service_.get();
175 void DeviceSettingsService::AddObserver(Observer* observer) {
176 observers_.AddObserver(observer);
179 void DeviceSettingsService::RemoveObserver(Observer* observer) {
180 observers_.RemoveObserver(observer);
183 void DeviceSettingsService::OwnerKeySet(bool success) {
184 if (!success) {
185 LOG(ERROR) << "Owner key change failed.";
186 return;
189 public_key_ = NULL;
190 EnsureReload(true);
193 void DeviceSettingsService::PropertyChangeComplete(bool success) {
194 if (!success) {
195 LOG(ERROR) << "Policy update failed.";
196 return;
199 EnsureReload(false);
202 void DeviceSettingsService::Enqueue(
203 const linked_ptr<SessionManagerOperation>& operation) {
204 pending_operations_.push_back(operation);
205 if (pending_operations_.front().get() == operation.get())
206 StartNextOperation();
209 void DeviceSettingsService::EnqueueLoad(bool force_key_load) {
210 linked_ptr<SessionManagerOperation> operation(new LoadSettingsOperation(
211 base::Bind(&DeviceSettingsService::HandleCompletedOperation,
212 weak_factory_.GetWeakPtr(),
213 base::Closure())));
214 operation->set_force_key_load(force_key_load);
215 Enqueue(operation);
218 void DeviceSettingsService::EnsureReload(bool force_key_load) {
219 if (!pending_operations_.empty())
220 pending_operations_.front()->RestartLoad(force_key_load);
221 else
222 EnqueueLoad(force_key_load);
225 void DeviceSettingsService::StartNextOperation() {
226 if (!pending_operations_.empty() && session_manager_client_ &&
227 owner_key_util_.get()) {
228 pending_operations_.front()->Start(
229 session_manager_client_, owner_key_util_, public_key_);
233 void DeviceSettingsService::HandleCompletedOperation(
234 const base::Closure& callback,
235 SessionManagerOperation* operation,
236 Status status) {
237 DCHECK_EQ(operation, pending_operations_.front().get());
238 store_status_ = status;
240 OwnershipStatus ownership_status = OWNERSHIP_UNKNOWN;
241 scoped_refptr<PublicKey> new_key(operation->public_key());
242 if (new_key.get()) {
243 ownership_status = new_key->is_loaded() ? OWNERSHIP_TAKEN : OWNERSHIP_NONE;
244 } else {
245 NOTREACHED() << "Failed to determine key status.";
248 bool new_owner_key = false;
249 if (public_key_.get() != new_key.get()) {
250 public_key_ = new_key;
251 new_owner_key = true;
254 if (status == STORE_SUCCESS) {
255 policy_data_ = operation->policy_data().Pass();
256 device_settings_ = operation->device_settings().Pass();
257 load_retries_left_ = kMaxLoadRetries;
258 } else if (status != STORE_KEY_UNAVAILABLE) {
259 LOG(ERROR) << "Session manager operation failed: " << status;
260 // Validation errors can be temporary if the rtc has gone on holiday for a
261 // short while. So we will retry such loads for up to 10 minutes.
262 if (status == STORE_TEMP_VALIDATION_ERROR) {
263 if (load_retries_left_ > 0) {
264 load_retries_left_--;
265 LOG(ERROR) << "A re-load has been scheduled due to a validation error.";
266 content::BrowserThread::PostDelayedTask(
267 content::BrowserThread::UI,
268 FROM_HERE,
269 base::Bind(&DeviceSettingsService::Load, base::Unretained(this)),
270 base::TimeDelta::FromMilliseconds(kLoadRetryDelayMs));
271 } else {
272 // Once we've given up retrying, the validation error is not temporary
273 // anymore.
274 store_status_ = STORE_VALIDATION_ERROR;
279 if (new_owner_key) {
280 FOR_EACH_OBSERVER(Observer, observers_, OwnershipStatusChanged());
281 content::NotificationService::current()->Notify(
282 chrome::NOTIFICATION_OWNERSHIP_STATUS_CHANGED,
283 content::Source<DeviceSettingsService>(this),
284 content::NotificationService::NoDetails());
287 FOR_EACH_OBSERVER(Observer, observers_, DeviceSettingsUpdated());
289 std::vector<OwnershipStatusCallback> callbacks;
290 callbacks.swap(pending_ownership_status_callbacks_);
291 for (std::vector<OwnershipStatusCallback>::iterator iter(callbacks.begin());
292 iter != callbacks.end(); ++iter) {
293 iter->Run(ownership_status);
296 // The completion callback happens after the notification so clients can
297 // filter self-triggered updates.
298 if (!callback.is_null())
299 callback.Run();
301 // Only remove the pending operation here, so new operations triggered by any
302 // of the callbacks above are queued up properly.
303 pending_operations_.pop_front();
305 StartNextOperation();
308 void DeviceSettingsService::HandleError(Status status,
309 const base::Closure& callback) {
310 store_status_ = status;
312 LOG(ERROR) << "Session manager operation failed: " << status;
314 FOR_EACH_OBSERVER(Observer, observers_, DeviceSettingsUpdated());
316 // The completion callback happens after the notification so clients can
317 // filter self-triggered updates.
318 if (!callback.is_null())
319 callback.Run();
322 ScopedTestDeviceSettingsService::ScopedTestDeviceSettingsService() {
323 DeviceSettingsService::Initialize();
326 ScopedTestDeviceSettingsService::~ScopedTestDeviceSettingsService() {
327 // Clean pending operations.
328 DeviceSettingsService::Get()->UnsetSessionManager();
329 DeviceSettingsService::Shutdown();
332 } // namespace chromeos