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