Disable view source for Developer Tools.
[chromium-blink-merge.git] / chrome / browser / chromeos / policy / device_status_collector.cc
blob2f0db684aaa256872446be4e99fff6120712882f
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/policy/device_status_collector.h"
7 #include <limits>
9 #include "base/bind.h"
10 #include "base/bind_helpers.h"
11 #include "base/command_line.h"
12 #include "base/location.h"
13 #include "base/logging.h"
14 #include "base/memory/scoped_ptr.h"
15 #include "base/prefs/pref_registry_simple.h"
16 #include "base/prefs/pref_service.h"
17 #include "base/prefs/scoped_user_pref_update.h"
18 #include "base/strings/string_number_conversions.h"
19 #include "base/values.h"
20 #include "chrome/browser/browser_process.h"
21 #include "chrome/browser/chromeos/login/user.h"
22 #include "chrome/browser/chromeos/login/user_manager.h"
23 #include "chrome/browser/chromeos/settings/cros_settings.h"
24 #include "chrome/browser/policy/browser_policy_connector.h"
25 #include "chrome/common/chrome_version_info.h"
26 #include "chrome/common/pref_names.h"
27 #include "chromeos/chromeos_switches.h"
28 #include "chromeos/network/device_state.h"
29 #include "chromeos/network/network_handler.h"
30 #include "chromeos/network/network_state_handler.h"
31 #include "chromeos/settings/cros_settings_names.h"
32 #include "chromeos/system/statistics_provider.h"
33 #include "components/policy/core/common/cloud/cloud_policy_constants.h"
34 #include "content/public/browser/browser_thread.h"
35 #include "policy/proto/device_management_backend.pb.h"
36 #include "third_party/cros_system_api/dbus/service_constants.h"
38 using base::Time;
39 using base::TimeDelta;
40 using chromeos::VersionLoader;
42 namespace em = enterprise_management;
44 namespace {
45 // How many seconds of inactivity triggers the idle state.
46 const int kIdleStateThresholdSeconds = 300;
48 // How many days in the past to store active periods for.
49 const unsigned int kMaxStoredPastActivityDays = 30;
51 // How many days in the future to store active periods for.
52 const unsigned int kMaxStoredFutureActivityDays = 2;
54 // How often, in seconds, to update the device location.
55 const unsigned int kGeolocationPollIntervalSeconds = 30 * 60;
57 const int64 kMillisecondsPerDay = Time::kMicrosecondsPerDay / 1000;
59 // Keys for the geolocation status dictionary in local state.
60 const char kLatitude[] = "latitude";
61 const char kLongitude[] = "longitude";
62 const char kAltitude[] = "altitude";
63 const char kAccuracy[] = "accuracy";
64 const char kAltitudeAccuracy[] = "altitude_accuracy";
65 const char kHeading[] = "heading";
66 const char kSpeed[] = "speed";
67 const char kTimestamp[] = "timestamp";
69 // Determine the day key (milliseconds since epoch for corresponding day in UTC)
70 // for a given |timestamp|.
71 int64 TimestampToDayKey(Time timestamp) {
72 Time::Exploded exploded;
73 timestamp.LocalMidnight().LocalExplode(&exploded);
74 return (Time::FromUTCExploded(exploded) - Time::UnixEpoch()).InMilliseconds();
77 // Maximum number of users to report.
78 const int kMaxUserCount = 5;
80 } // namespace
82 namespace policy {
84 DeviceStatusCollector::Context::Context() {
87 DeviceStatusCollector::Context::~Context() {
90 void DeviceStatusCollector::Context::GetLocationUpdate(
91 const content::GeolocationProvider::LocationUpdateCallback& callback) {
92 owner_callback_ = callback;
93 content::BrowserThread::PostTask(
94 content::BrowserThread::IO,
95 FROM_HERE,
96 base::Bind(&DeviceStatusCollector::Context::GetLocationUpdateInternal,
97 this));
100 void DeviceStatusCollector::Context::GetLocationUpdateInternal() {
101 our_callback_ = base::Bind(
102 &DeviceStatusCollector::Context::OnLocationUpdate, this);
103 content::GeolocationProvider::GetInstance()->AddLocationUpdateCallback(
104 our_callback_, true);
107 void DeviceStatusCollector::Context::OnLocationUpdate(
108 const content::Geoposition& geoposition) {
109 content::GeolocationProvider::GetInstance()->RemoveLocationUpdateCallback(
110 our_callback_);
111 our_callback_.Reset();
112 content::BrowserThread::PostTask(
113 content::BrowserThread::UI,
114 FROM_HERE,
115 base::Bind(&DeviceStatusCollector::Context::CallCollector,
116 this, geoposition));
119 void DeviceStatusCollector::Context::CallCollector(
120 const content::Geoposition& geoposition) {
121 owner_callback_.Run(geoposition);
122 owner_callback_.Reset();
125 DeviceStatusCollector::DeviceStatusCollector(
126 PrefService* local_state,
127 chromeos::system::StatisticsProvider* provider,
128 LocationUpdateRequester* location_update_requester)
129 : max_stored_past_activity_days_(kMaxStoredPastActivityDays),
130 max_stored_future_activity_days_(kMaxStoredFutureActivityDays),
131 local_state_(local_state),
132 last_idle_check_(Time()),
133 last_reported_day_(0),
134 duration_for_last_reported_day_(0),
135 geolocation_update_in_progress_(false),
136 statistics_provider_(provider),
137 weak_factory_(this),
138 report_version_info_(false),
139 report_activity_times_(false),
140 report_boot_mode_(false),
141 report_location_(false),
142 report_network_interfaces_(false),
143 report_users_(false),
144 context_(new Context()) {
145 if (location_update_requester) {
146 location_update_requester_ = *location_update_requester;
147 } else {
148 location_update_requester_ =
149 base::Bind(&Context::GetLocationUpdate, context_.get());
151 idle_poll_timer_.Start(FROM_HERE,
152 TimeDelta::FromSeconds(kIdlePollIntervalSeconds),
153 this, &DeviceStatusCollector::CheckIdleState);
155 cros_settings_ = chromeos::CrosSettings::Get();
157 // Watch for changes to the individual policies that control what the status
158 // reports contain.
159 base::Closure callback =
160 base::Bind(&DeviceStatusCollector::UpdateReportingSettings,
161 base::Unretained(this));
162 version_info_subscription_ = cros_settings_->AddSettingsObserver(
163 chromeos::kReportDeviceVersionInfo, callback);
164 activity_times_subscription_ = cros_settings_->AddSettingsObserver(
165 chromeos::kReportDeviceActivityTimes, callback);
166 boot_mode_subscription_ = cros_settings_->AddSettingsObserver(
167 chromeos::kReportDeviceBootMode, callback);
168 location_subscription_ = cros_settings_->AddSettingsObserver(
169 chromeos::kReportDeviceLocation, callback);
170 network_interfaces_subscription_ = cros_settings_->AddSettingsObserver(
171 chromeos::kReportDeviceNetworkInterfaces, callback);
172 users_subscription_ = cros_settings_->AddSettingsObserver(
173 chromeos::kReportDeviceUsers, callback);
175 // The last known location is persisted in local state. This makes location
176 // information available immediately upon startup and avoids the need to
177 // reacquire the location on every user session change or browser crash.
178 content::Geoposition position;
179 std::string timestamp_str;
180 int64 timestamp;
181 const base::DictionaryValue* location =
182 local_state_->GetDictionary(prefs::kDeviceLocation);
183 if (location->GetDouble(kLatitude, &position.latitude) &&
184 location->GetDouble(kLongitude, &position.longitude) &&
185 location->GetDouble(kAltitude, &position.altitude) &&
186 location->GetDouble(kAccuracy, &position.accuracy) &&
187 location->GetDouble(kAltitudeAccuracy, &position.altitude_accuracy) &&
188 location->GetDouble(kHeading, &position.heading) &&
189 location->GetDouble(kSpeed, &position.speed) &&
190 location->GetString(kTimestamp, &timestamp_str) &&
191 base::StringToInt64(timestamp_str, &timestamp)) {
192 position.timestamp = Time::FromInternalValue(timestamp);
193 position_ = position;
196 // Fetch the current values of the policies.
197 UpdateReportingSettings();
199 // Get the the OS and firmware version info.
200 version_loader_.GetVersion(
201 VersionLoader::VERSION_FULL,
202 base::Bind(&DeviceStatusCollector::OnOSVersion, base::Unretained(this)),
203 &tracker_);
204 version_loader_.GetFirmware(
205 base::Bind(&DeviceStatusCollector::OnOSFirmware, base::Unretained(this)),
206 &tracker_);
209 DeviceStatusCollector::~DeviceStatusCollector() {
212 // static
213 void DeviceStatusCollector::RegisterPrefs(PrefRegistrySimple* registry) {
214 registry->RegisterDictionaryPref(prefs::kDeviceActivityTimes,
215 new base::DictionaryValue);
216 registry->RegisterDictionaryPref(prefs::kDeviceLocation,
217 new base::DictionaryValue);
220 void DeviceStatusCollector::CheckIdleState() {
221 CalculateIdleState(kIdleStateThresholdSeconds,
222 base::Bind(&DeviceStatusCollector::IdleStateCallback,
223 base::Unretained(this)));
226 void DeviceStatusCollector::UpdateReportingSettings() {
227 // Attempt to fetch the current value of the reporting settings.
228 // If trusted values are not available, register this function to be called
229 // back when they are available.
230 if (chromeos::CrosSettingsProvider::TRUSTED !=
231 cros_settings_->PrepareTrustedValues(
232 base::Bind(&DeviceStatusCollector::UpdateReportingSettings,
233 weak_factory_.GetWeakPtr()))) {
234 return;
236 cros_settings_->GetBoolean(
237 chromeos::kReportDeviceVersionInfo, &report_version_info_);
238 cros_settings_->GetBoolean(
239 chromeos::kReportDeviceActivityTimes, &report_activity_times_);
240 cros_settings_->GetBoolean(
241 chromeos::kReportDeviceBootMode, &report_boot_mode_);
242 cros_settings_->GetBoolean(
243 chromeos::kReportDeviceLocation, &report_location_);
244 cros_settings_->GetBoolean(
245 chromeos::kReportDeviceNetworkInterfaces, &report_network_interfaces_);
246 cros_settings_->GetBoolean(
247 chromeos::kReportDeviceUsers, &report_users_);
249 if (report_location_) {
250 ScheduleGeolocationUpdateRequest();
251 } else {
252 geolocation_update_timer_.Stop();
253 position_ = content::Geoposition();
254 local_state_->ClearPref(prefs::kDeviceLocation);
258 Time DeviceStatusCollector::GetCurrentTime() {
259 return Time::Now();
262 // Remove all out-of-range activity times from the local store.
263 void DeviceStatusCollector::PruneStoredActivityPeriods(Time base_time) {
264 Time min_time =
265 base_time - TimeDelta::FromDays(max_stored_past_activity_days_);
266 Time max_time =
267 base_time + TimeDelta::FromDays(max_stored_future_activity_days_);
268 TrimStoredActivityPeriods(TimestampToDayKey(min_time), 0,
269 TimestampToDayKey(max_time));
272 void DeviceStatusCollector::TrimStoredActivityPeriods(int64 min_day_key,
273 int min_day_trim_duration,
274 int64 max_day_key) {
275 const base::DictionaryValue* activity_times =
276 local_state_->GetDictionary(prefs::kDeviceActivityTimes);
278 scoped_ptr<base::DictionaryValue> copy(activity_times->DeepCopy());
279 for (base::DictionaryValue::Iterator it(*activity_times); !it.IsAtEnd();
280 it.Advance()) {
281 int64 timestamp;
282 if (base::StringToInt64(it.key(), &timestamp)) {
283 // Remove data that is too old, or too far in the future.
284 if (timestamp >= min_day_key && timestamp < max_day_key) {
285 if (timestamp == min_day_key) {
286 int new_activity_duration = 0;
287 if (it.value().GetAsInteger(&new_activity_duration)) {
288 new_activity_duration =
289 std::max(new_activity_duration - min_day_trim_duration, 0);
291 copy->SetInteger(it.key(), new_activity_duration);
293 continue;
296 // The entry is out of range or couldn't be parsed. Remove it.
297 copy->Remove(it.key(), NULL);
299 local_state_->Set(prefs::kDeviceActivityTimes, *copy);
302 void DeviceStatusCollector::AddActivePeriod(Time start, Time end) {
303 DCHECK(start < end);
305 // Maintain the list of active periods in a local_state pref.
306 DictionaryPrefUpdate update(local_state_, prefs::kDeviceActivityTimes);
307 base::DictionaryValue* activity_times = update.Get();
309 // Assign the period to day buckets in local time.
310 Time midnight = start.LocalMidnight();
311 while (midnight < end) {
312 midnight += TimeDelta::FromDays(1);
313 int64 activity = (std::min(end, midnight) - start).InMilliseconds();
314 std::string day_key = base::Int64ToString(TimestampToDayKey(start));
315 int previous_activity = 0;
316 activity_times->GetInteger(day_key, &previous_activity);
317 activity_times->SetInteger(day_key, previous_activity + activity);
318 start = midnight;
322 void DeviceStatusCollector::IdleStateCallback(IdleState state) {
323 // Do nothing if device activity reporting is disabled.
324 if (!report_activity_times_)
325 return;
327 Time now = GetCurrentTime();
329 if (state == IDLE_STATE_ACTIVE) {
330 // If it's been too long since the last report, or if the activity is
331 // negative (which can happen when the clock changes), assume a single
332 // interval of activity.
333 int active_seconds = (now - last_idle_check_).InSeconds();
334 if (active_seconds < 0 ||
335 active_seconds >= static_cast<int>((2 * kIdlePollIntervalSeconds))) {
336 AddActivePeriod(now - TimeDelta::FromSeconds(kIdlePollIntervalSeconds),
337 now);
338 } else {
339 AddActivePeriod(last_idle_check_, now);
342 PruneStoredActivityPeriods(now);
344 last_idle_check_ = now;
347 void DeviceStatusCollector::GetActivityTimes(
348 em::DeviceStatusReportRequest* request) {
349 DictionaryPrefUpdate update(local_state_, prefs::kDeviceActivityTimes);
350 base::DictionaryValue* activity_times = update.Get();
352 for (base::DictionaryValue::Iterator it(*activity_times); !it.IsAtEnd();
353 it.Advance()) {
354 int64 start_timestamp;
355 int activity_milliseconds;
356 if (base::StringToInt64(it.key(), &start_timestamp) &&
357 it.value().GetAsInteger(&activity_milliseconds)) {
358 // This is correct even when there are leap seconds, because when a leap
359 // second occurs, two consecutive seconds have the same timestamp.
360 int64 end_timestamp = start_timestamp + kMillisecondsPerDay;
362 em::ActiveTimePeriod* active_period = request->add_active_period();
363 em::TimePeriod* period = active_period->mutable_time_period();
364 period->set_start_timestamp(start_timestamp);
365 period->set_end_timestamp(end_timestamp);
366 active_period->set_active_duration(activity_milliseconds);
367 if (start_timestamp >= last_reported_day_) {
368 last_reported_day_ = start_timestamp;
369 duration_for_last_reported_day_ = activity_milliseconds;
371 } else {
372 NOTREACHED();
377 void DeviceStatusCollector::GetVersionInfo(
378 em::DeviceStatusReportRequest* request) {
379 chrome::VersionInfo version_info;
380 request->set_browser_version(version_info.Version());
381 request->set_os_version(os_version_);
382 request->set_firmware_version(firmware_version_);
385 void DeviceStatusCollector::GetBootMode(
386 em::DeviceStatusReportRequest* request) {
387 std::string dev_switch_mode;
388 if (statistics_provider_->GetMachineStatistic(
389 chromeos::system::kDevSwitchBootMode, &dev_switch_mode)) {
390 if (dev_switch_mode == "1")
391 request->set_boot_mode("Dev");
392 else if (dev_switch_mode == "0")
393 request->set_boot_mode("Verified");
397 void DeviceStatusCollector::GetLocation(
398 em::DeviceStatusReportRequest* request) {
399 em::DeviceLocation* location = request->mutable_device_location();
400 if (!position_.Validate()) {
401 location->set_error_code(
402 em::DeviceLocation::ERROR_CODE_POSITION_UNAVAILABLE);
403 location->set_error_message(position_.error_message);
404 } else {
405 location->set_latitude(position_.latitude);
406 location->set_longitude(position_.longitude);
407 location->set_accuracy(position_.accuracy);
408 location->set_timestamp(
409 (position_.timestamp - Time::UnixEpoch()).InMilliseconds());
410 // Lowest point on land is at approximately -400 meters.
411 if (position_.altitude > -10000.)
412 location->set_altitude(position_.altitude);
413 if (position_.altitude_accuracy >= 0.)
414 location->set_altitude_accuracy(position_.altitude_accuracy);
415 if (position_.heading >= 0. && position_.heading <= 360)
416 location->set_heading(position_.heading);
417 if (position_.speed >= 0.)
418 location->set_speed(position_.speed);
419 location->set_error_code(em::DeviceLocation::ERROR_CODE_NONE);
423 void DeviceStatusCollector::GetNetworkInterfaces(
424 em::DeviceStatusReportRequest* request) {
425 // Maps flimflam device type strings to proto enum constants.
426 static const struct {
427 const char* type_string;
428 em::NetworkInterface::NetworkDeviceType type_constant;
429 } kDeviceTypeMap[] = {
430 { shill::kTypeEthernet, em::NetworkInterface::TYPE_ETHERNET, },
431 { shill::kTypeWifi, em::NetworkInterface::TYPE_WIFI, },
432 { shill::kTypeWimax, em::NetworkInterface::TYPE_WIMAX, },
433 { shill::kTypeBluetooth, em::NetworkInterface::TYPE_BLUETOOTH, },
434 { shill::kTypeCellular, em::NetworkInterface::TYPE_CELLULAR, },
437 chromeos::NetworkStateHandler::DeviceStateList device_list;
438 chromeos::NetworkHandler::Get()->network_state_handler()->GetDeviceList(
439 &device_list);
441 chromeos::NetworkStateHandler::DeviceStateList::const_iterator device;
442 for (device = device_list.begin(); device != device_list.end(); ++device) {
443 // Determine the type enum constant for |device|.
444 size_t type_idx = 0;
445 for (; type_idx < ARRAYSIZE_UNSAFE(kDeviceTypeMap); ++type_idx) {
446 if ((*device)->type() == kDeviceTypeMap[type_idx].type_string)
447 break;
450 // If the type isn't in |kDeviceTypeMap|, the interface is not relevant for
451 // reporting. This filters out VPN devices.
452 if (type_idx >= ARRAYSIZE_UNSAFE(kDeviceTypeMap))
453 continue;
455 em::NetworkInterface* interface = request->add_network_interface();
456 interface->set_type(kDeviceTypeMap[type_idx].type_constant);
457 if (!(*device)->mac_address().empty())
458 interface->set_mac_address((*device)->mac_address());
459 if (!(*device)->meid().empty())
460 interface->set_meid((*device)->meid());
461 if (!(*device)->imei().empty())
462 interface->set_imei((*device)->imei());
466 void DeviceStatusCollector::GetUsers(em::DeviceStatusReportRequest* request) {
467 BrowserPolicyConnector* connector =
468 g_browser_process->browser_policy_connector();
469 bool found_managed_user = false;
470 const chromeos::UserList& users = chromeos::UserManager::Get()->GetUsers();
471 chromeos::UserList::const_iterator user;
472 for (user = users.begin(); user != users.end(); ++user) {
473 // Only regular users are reported.
474 if ((*user)->GetType() != chromeos::User::USER_TYPE_REGULAR)
475 continue;
477 em::DeviceUser* device_user = request->add_user();
478 const std::string& email = (*user)->email();
479 if (connector->GetUserAffiliation(email) == USER_AFFILIATION_MANAGED) {
480 device_user->set_type(em::DeviceUser::USER_TYPE_MANAGED);
481 device_user->set_email(email);
482 found_managed_user = true;
483 } else {
484 device_user->set_type(em::DeviceUser::USER_TYPE_UNMANAGED);
485 // Do not report the email address of unmanaged users.
488 // Add only kMaxUserCount entries, unless no managed users are found in the
489 // first kMaxUserCount users. In that case, continue until at least one
490 // managed user is found.
491 if (request->user_size() >= kMaxUserCount && found_managed_user)
492 break;
496 void DeviceStatusCollector::GetStatus(em::DeviceStatusReportRequest* request) {
497 // TODO(mnissler): Remove once the old cloud policy stack is retired. The old
498 // stack doesn't support reporting successful submissions back to here, so
499 // just assume whatever ends up in |request| gets submitted successfully.
500 GetDeviceStatus(request);
501 OnSubmittedSuccessfully();
504 bool DeviceStatusCollector::GetDeviceStatus(
505 em::DeviceStatusReportRequest* status) {
506 if (report_activity_times_)
507 GetActivityTimes(status);
509 if (report_version_info_)
510 GetVersionInfo(status);
512 if (report_boot_mode_)
513 GetBootMode(status);
515 if (report_location_)
516 GetLocation(status);
518 if (report_network_interfaces_)
519 GetNetworkInterfaces(status);
521 if (report_users_ && !CommandLine::ForCurrentProcess()->HasSwitch(
522 chromeos::switches::kDisableEnterpriseUserReporting)) {
523 GetUsers(status);
526 return true;
529 bool DeviceStatusCollector::GetSessionStatus(
530 em::SessionStatusReportRequest* status) {
531 return false;
534 void DeviceStatusCollector::OnSubmittedSuccessfully() {
535 TrimStoredActivityPeriods(last_reported_day_, duration_for_last_reported_day_,
536 std::numeric_limits<int64>::max());
539 void DeviceStatusCollector::OnOSVersion(const std::string& version) {
540 os_version_ = version;
543 void DeviceStatusCollector::OnOSFirmware(const std::string& version) {
544 firmware_version_ = version;
547 void DeviceStatusCollector::ScheduleGeolocationUpdateRequest() {
548 if (geolocation_update_timer_.IsRunning() || geolocation_update_in_progress_)
549 return;
551 if (position_.Validate()) {
552 TimeDelta elapsed = GetCurrentTime() - position_.timestamp;
553 TimeDelta interval =
554 TimeDelta::FromSeconds(kGeolocationPollIntervalSeconds);
555 if (elapsed > interval) {
556 geolocation_update_in_progress_ = true;
557 location_update_requester_.Run(base::Bind(
558 &DeviceStatusCollector::ReceiveGeolocationUpdate,
559 weak_factory_.GetWeakPtr()));
560 } else {
561 geolocation_update_timer_.Start(
562 FROM_HERE,
563 interval - elapsed,
564 this,
565 &DeviceStatusCollector::ScheduleGeolocationUpdateRequest);
567 } else {
568 geolocation_update_in_progress_ = true;
569 location_update_requester_.Run(base::Bind(
570 &DeviceStatusCollector::ReceiveGeolocationUpdate,
571 weak_factory_.GetWeakPtr()));
575 void DeviceStatusCollector::ReceiveGeolocationUpdate(
576 const content::Geoposition& position) {
577 geolocation_update_in_progress_ = false;
579 // Ignore update if device location reporting has since been disabled.
580 if (!report_location_)
581 return;
583 if (position.Validate()) {
584 position_ = position;
585 base::DictionaryValue location;
586 location.SetDouble(kLatitude, position.latitude);
587 location.SetDouble(kLongitude, position.longitude);
588 location.SetDouble(kAltitude, position.altitude);
589 location.SetDouble(kAccuracy, position.accuracy);
590 location.SetDouble(kAltitudeAccuracy, position.altitude_accuracy);
591 location.SetDouble(kHeading, position.heading);
592 location.SetDouble(kSpeed, position.speed);
593 location.SetString(kTimestamp,
594 base::Int64ToString(position.timestamp.ToInternalValue()));
595 local_state_->Set(prefs::kDeviceLocation, location);
598 ScheduleGeolocationUpdateRequest();
601 } // namespace policy