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