Update To 11.40.268.0
[platform/framework/web/crosswalk.git] / src / chrome / browser / chromeos / settings / device_settings_service.cc
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "chrome/browser/chromeos/settings/device_settings_service.h"
6
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"
22
23 namespace em = enterprise_management;
24
25 using ownership::OwnerKeyUtil;
26 using ownership::PublicKey;
27
28 namespace {
29
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;
38
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)
45     return true;
46
47   switch (current_mode) {
48     case em::PolicyData::NOT_MANAGED:
49       // For consumer management enrollment.
50       return new_mode == em::PolicyData::CONSUMER_MANAGED;
51
52     case em::PolicyData::ENTERPRISE_MANAGED:
53       // Management mode cannot be set when it is currently ENTERPRISE_MANAGED.
54       return false;
55
56     case em::PolicyData::CONSUMER_MANAGED:
57       // For consumer management unenrollment.
58       return new_mode == em::PolicyData::NOT_MANAGED;
59   }
60
61   NOTREACHED();
62   return false;
63 }
64
65 }  // namespace
66
67 namespace chromeos {
68
69 DeviceSettingsService::Observer::~Observer() {}
70
71 static DeviceSettingsService* g_device_settings_service = NULL;
72
73 // static
74 void DeviceSettingsService::Initialize() {
75   CHECK(!g_device_settings_service);
76   g_device_settings_service = new DeviceSettingsService();
77 }
78
79 // static
80 bool DeviceSettingsService::IsInitialized() {
81   return g_device_settings_service;
82 }
83
84 // static
85 void DeviceSettingsService::Shutdown() {
86   DCHECK(g_device_settings_service);
87   delete g_device_settings_service;
88   g_device_settings_service = NULL;
89 }
90
91 // static
92 DeviceSettingsService* DeviceSettingsService::Get() {
93   CHECK(g_device_settings_service);
94   return g_device_settings_service;
95 }
96
97 DeviceSettingsService::DeviceSettingsService()
98     : session_manager_client_(NULL),
99       store_status_(STORE_SUCCESS),
100       load_retries_left_(kMaxLoadRetries),
101       weak_factory_(this) {
102 }
103
104 DeviceSettingsService::~DeviceSettingsService() {
105   DCHECK(pending_operations_.empty());
106   FOR_EACH_OBSERVER(Observer, observers_, OnDeviceSettingsServiceShutdown());
107 }
108
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());
116
117   session_manager_client_ = session_manager_client;
118   owner_key_util_ = owner_key_util;
119
120   session_manager_client_->AddObserver(this);
121
122   StartNextOperation();
123 }
124
125 void DeviceSettingsService::UnsetSessionManager() {
126   pending_operations_.clear();
127
128   if (session_manager_client_)
129     session_manager_client_->RemoveObserver(this);
130   session_manager_client_ = NULL;
131   owner_key_util_ = NULL;
132 }
133
134 scoped_refptr<PublicKey> DeviceSettingsService::GetPublicKey() {
135   return public_key_;
136 }
137
138 void DeviceSettingsService::Load() {
139   EnqueueLoad(false);
140 }
141
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);
149 }
150
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);
158     return;
159   }
160
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();
164
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);
169     return;
170   }
171
172   scoped_ptr<em::PolicyData> policy =
173       OwnerSettingsServiceChromeOS::AssemblePolicy(
174           GetUsername(), policy_data(), device_settings());
175   if (!policy) {
176     HandleError(DeviceSettingsService::STORE_POLICY_ERROR, callback);
177     return;
178   }
179
180   policy->set_management_mode(management_mode);
181   policy->set_request_token(request_token);
182   policy->set_device_id(device_id);
183
184   EnqueueSignAndStore(policy.Pass(), callback);
185 }
186
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(),
192                  callback),
193       policy.Pass())));
194 }
195
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;
201 }
202
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()));
209   } else {
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())
215       EnqueueLoad(false);
216   }
217 }
218
219 bool DeviceSettingsService::HasPrivateOwnerKey() {
220   return owner_settings_service_ && owner_settings_service_->IsOwner();
221 }
222
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)
230     return;
231   username_ = username;
232   owner_settings_service_ = owner_settings_service;
233
234   EnsureReload(true);
235 }
236
237 const std::string& DeviceSettingsService::GetUsername() const {
238   return username_;
239 }
240
241 ownership::OwnerSettingsService*
242 DeviceSettingsService::GetOwnerSettingsService() const {
243   return owner_settings_service_.get();
244 }
245
246 void DeviceSettingsService::AddObserver(Observer* observer) {
247   observers_.AddObserver(observer);
248 }
249
250 void DeviceSettingsService::RemoveObserver(Observer* observer) {
251   observers_.RemoveObserver(observer);
252 }
253
254 void DeviceSettingsService::OwnerKeySet(bool success) {
255   if (!success) {
256     LOG(ERROR) << "Owner key change failed.";
257     return;
258   }
259
260   public_key_ = NULL;
261   EnsureReload(true);
262 }
263
264 void DeviceSettingsService::PropertyChangeComplete(bool success) {
265   if (!success) {
266     LOG(ERROR) << "Policy update failed.";
267     return;
268   }
269
270   EnsureReload(false);
271 }
272
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();
278 }
279
280 void DeviceSettingsService::EnqueueLoad(bool force_key_load) {
281   linked_ptr<SessionManagerOperation> operation(new LoadSettingsOperation(
282       base::Bind(&DeviceSettingsService::HandleCompletedOperation,
283                  weak_factory_.GetWeakPtr(),
284                  base::Closure())));
285   operation->set_force_key_load(force_key_load);
286   operation->set_username(username_);
287   operation->set_owner_settings_service(owner_settings_service_);
288   Enqueue(operation);
289 }
290
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(),
298                      callback),
299           policy.Pass()));
300   operation->set_owner_settings_service(owner_settings_service_);
301   Enqueue(operation);
302 }
303
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);
310   } else {
311     EnqueueLoad(force_key_load);
312   }
313 }
314
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_);
320   }
321 }
322
323 void DeviceSettingsService::HandleCompletedOperation(
324     const base::Closure& callback,
325     SessionManagerOperation* operation,
326     Status status) {
327   DCHECK_EQ(operation, pending_operations_.front().get());
328   store_status_ = status;
329
330   OwnershipStatus ownership_status = OWNERSHIP_UNKNOWN;
331   scoped_refptr<PublicKey> new_key(operation->public_key());
332   if (new_key.get()) {
333     ownership_status = new_key->is_loaded() ? OWNERSHIP_TAKEN : OWNERSHIP_NONE;
334   } else {
335     NOTREACHED() << "Failed to determine key status.";
336   }
337
338   bool new_owner_key = false;
339   if (public_key_.get() != new_key.get()) {
340     public_key_ = new_key;
341     new_owner_key = true;
342   }
343
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,
358             FROM_HERE,
359             base::Bind(&DeviceSettingsService::Load, base::Unretained(this)),
360             base::TimeDelta::FromMilliseconds(kLoadRetryDelayMs));
361       } else {
362         // Once we've given up retrying, the validation error is not temporary
363         // anymore.
364         store_status_ = STORE_VALIDATION_ERROR;
365       }
366     }
367   }
368
369   if (new_owner_key) {
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());
375   }
376
377   FOR_EACH_OBSERVER(Observer, observers_, DeviceSettingsUpdated());
378
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);
384   }
385
386   // The completion callback happens after the notification so clients can
387   // filter self-triggered updates.
388   if (!callback.is_null())
389     callback.Run();
390
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();
394
395   StartNextOperation();
396 }
397
398 void DeviceSettingsService::HandleError(Status status,
399                                         const base::Closure& callback) {
400   store_status_ = status;
401
402   LOG(ERROR) << "Session manager operation failed: " << status;
403
404   FOR_EACH_OBSERVER(Observer, observers_, DeviceSettingsUpdated());
405
406   // The completion callback happens after the notification so clients can
407   // filter self-triggered updates.
408   if (!callback.is_null())
409     callback.Run();
410 }
411
412 ScopedTestDeviceSettingsService::ScopedTestDeviceSettingsService() {
413   DeviceSettingsService::Initialize();
414 }
415
416 ScopedTestDeviceSettingsService::~ScopedTestDeviceSettingsService() {
417   // Clean pending operations.
418   DeviceSettingsService::Get()->UnsetSessionManager();
419   DeviceSettingsService::Shutdown();
420 }
421
422 }  // namespace chromeos