ozone: evdev: Sync caps lock LED state to evdev
[chromium-blink-merge.git] / chrome / browser / chromeos / policy / device_status_collector.cc
blobfcba06b16120eba706dd20973e4dc4e1be4f51a7
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 <stdint.h>
8 #include <limits>
9 #include <sys/statvfs.h>
11 #include "base/bind.h"
12 #include "base/bind_helpers.h"
13 #include "base/location.h"
14 #include "base/logging.h"
15 #include "base/memory/scoped_ptr.h"
16 #include "base/posix/eintr_wrapper.h"
17 #include "base/prefs/pref_registry_simple.h"
18 #include "base/prefs/pref_service.h"
19 #include "base/prefs/scoped_user_pref_update.h"
20 #include "base/process/process.h"
21 #include "base/process/process_iterator.h"
22 #include "base/process/process_metrics.h"
23 #include "base/strings/string_number_conversions.h"
24 #include "base/sys_info.h"
25 #include "base/task_runner_util.h"
26 #include "base/values.h"
27 #include "chrome/browser/browser_process.h"
28 #include "chrome/browser/chromeos/app_mode/kiosk_app_manager.h"
29 #include "chrome/browser/chromeos/policy/browser_policy_connector_chromeos.h"
30 #include "chrome/browser/chromeos/policy/device_local_account.h"
31 #include "chrome/browser/chromeos/profiles/profile_helper.h"
32 #include "chrome/browser/chromeos/settings/cros_settings.h"
33 #include "chrome/common/chrome_version_info.h"
34 #include "chrome/common/pref_names.h"
35 #include "chromeos/disks/disk_mount_manager.h"
36 #include "chromeos/network/device_state.h"
37 #include "chromeos/network/network_handler.h"
38 #include "chromeos/network/network_state.h"
39 #include "chromeos/network/network_state_handler.h"
40 #include "chromeos/settings/cros_settings_names.h"
41 #include "chromeos/system/statistics_provider.h"
42 #include "components/policy/core/common/cloud/cloud_policy_constants.h"
43 #include "components/user_manager/user.h"
44 #include "components/user_manager/user_manager.h"
45 #include "components/user_manager/user_type.h"
46 #include "content/public/browser/browser_thread.h"
47 #include "extensions/browser/extension_registry.h"
48 #include "extensions/common/extension.h"
49 #include "policy/proto/device_management_backend.pb.h"
50 #include "third_party/cros_system_api/dbus/service_constants.h"
52 using base::Time;
53 using base::TimeDelta;
55 namespace em = enterprise_management;
57 namespace {
58 // How many seconds of inactivity triggers the idle state.
59 const int kIdleStateThresholdSeconds = 300;
61 // How many days in the past to store active periods for.
62 const unsigned int kMaxStoredPastActivityDays = 30;
64 // How many days in the future to store active periods for.
65 const unsigned int kMaxStoredFutureActivityDays = 2;
67 // How often, in seconds, to update the device location.
68 const unsigned int kGeolocationPollIntervalSeconds = 30 * 60;
70 // How often, in seconds, to sample the hardware state.
71 static const unsigned int kHardwareStatusSampleIntervalSeconds = 120;
73 const int64 kMillisecondsPerDay = Time::kMicrosecondsPerDay / 1000;
75 // Keys for the geolocation status dictionary in local state.
76 const char kLatitude[] = "latitude";
77 const char kLongitude[] = "longitude";
78 const char kAltitude[] = "altitude";
79 const char kAccuracy[] = "accuracy";
80 const char kAltitudeAccuracy[] = "altitude_accuracy";
81 const char kHeading[] = "heading";
82 const char kSpeed[] = "speed";
83 const char kTimestamp[] = "timestamp";
85 // Determine the day key (milliseconds since epoch for corresponding day in UTC)
86 // for a given |timestamp|.
87 int64 TimestampToDayKey(Time timestamp) {
88 Time::Exploded exploded;
89 timestamp.LocalMidnight().LocalExplode(&exploded);
90 return (Time::FromUTCExploded(exploded) - Time::UnixEpoch()).InMilliseconds();
93 // Helper function (invoked via blocking pool) to fetch information about
94 // mounted disks.
95 std::vector<em::VolumeInfo> GetVolumeInfo(
96 const std::vector<std::string>& mount_points) {
97 std::vector<em::VolumeInfo> result;
98 for (const std::string& mount_point : mount_points) {
99 struct statvfs stat = {}; // Zero-clear
100 if (HANDLE_EINTR(statvfs(mount_point.c_str(), &stat)) == 0) {
101 em::VolumeInfo info;
102 info.set_volume_id(mount_point);
103 info.set_storage_total(static_cast<int64_t>(stat.f_blocks) *
104 stat.f_frsize);
105 info.set_storage_free(static_cast<uint64_t>(stat.f_bavail) *
106 stat.f_frsize);
107 result.push_back(info);
108 } else {
109 LOG(ERROR) << "Unable to get volume status for " << mount_point;
112 return result;
115 // Returns the DeviceLocalAccount associated with the current kiosk session.
116 // Returns null if there is no active kiosk session, or if that kiosk
117 // session has been removed from policy since the session started, in which
118 // case we won't report its status).
119 scoped_ptr<policy::DeviceLocalAccount>
120 GetCurrentKioskDeviceLocalAccount(chromeos::CrosSettings* settings) {
121 if (!user_manager::UserManager::Get()->IsLoggedInAsKioskApp())
122 return scoped_ptr<policy::DeviceLocalAccount>();
123 const user_manager::User* const user =
124 user_manager::UserManager::Get()->GetActiveUser();
125 const std::string user_id = user->GetUserID();
126 const std::vector<policy::DeviceLocalAccount> accounts =
127 policy::GetDeviceLocalAccounts(settings);
129 for (const auto& device_local_account : accounts) {
130 if (device_local_account.user_id == user_id) {
131 return make_scoped_ptr(
132 new policy::DeviceLocalAccount(device_local_account)).Pass();
135 LOG(WARNING) << "Kiosk app not found in list of device-local accounts";
136 return scoped_ptr<policy::DeviceLocalAccount>();
139 } // namespace
141 namespace policy {
143 DeviceStatusCollector::DeviceStatusCollector(
144 PrefService* local_state,
145 chromeos::system::StatisticsProvider* provider,
146 const LocationUpdateRequester& location_update_requester,
147 const VolumeInfoFetcher& volume_info_fetcher)
148 : max_stored_past_activity_days_(kMaxStoredPastActivityDays),
149 max_stored_future_activity_days_(kMaxStoredFutureActivityDays),
150 local_state_(local_state),
151 last_idle_check_(Time()),
152 last_reported_day_(0),
153 duration_for_last_reported_day_(0),
154 geolocation_update_in_progress_(false),
155 volume_info_fetcher_(volume_info_fetcher),
156 statistics_provider_(provider),
157 location_update_requester_(location_update_requester),
158 report_version_info_(false),
159 report_activity_times_(false),
160 report_boot_mode_(false),
161 report_location_(false),
162 report_network_interfaces_(false),
163 report_users_(false),
164 report_hardware_status_(false),
165 report_session_status_(false),
166 weak_factory_(this) {
167 if (volume_info_fetcher_.is_null())
168 volume_info_fetcher_ = base::Bind(&GetVolumeInfo);
170 idle_poll_timer_.Start(FROM_HERE,
171 TimeDelta::FromSeconds(kIdlePollIntervalSeconds),
172 this, &DeviceStatusCollector::CheckIdleState);
173 hardware_status_sampling_timer_.Start(
174 FROM_HERE,
175 TimeDelta::FromSeconds(kHardwareStatusSampleIntervalSeconds),
176 this, &DeviceStatusCollector::SampleHardwareStatus);
178 cros_settings_ = chromeos::CrosSettings::Get();
181 // Watch for changes to the individual policies that control what the status
182 // reports contain.
183 base::Closure callback =
184 base::Bind(&DeviceStatusCollector::UpdateReportingSettings,
185 base::Unretained(this));
186 version_info_subscription_ = cros_settings_->AddSettingsObserver(
187 chromeos::kReportDeviceVersionInfo, callback);
188 activity_times_subscription_ = cros_settings_->AddSettingsObserver(
189 chromeos::kReportDeviceActivityTimes, callback);
190 boot_mode_subscription_ = cros_settings_->AddSettingsObserver(
191 chromeos::kReportDeviceBootMode, callback);
192 location_subscription_ = cros_settings_->AddSettingsObserver(
193 chromeos::kReportDeviceLocation, callback);
194 network_interfaces_subscription_ = cros_settings_->AddSettingsObserver(
195 chromeos::kReportDeviceNetworkInterfaces, callback);
196 users_subscription_ = cros_settings_->AddSettingsObserver(
197 chromeos::kReportDeviceUsers, callback);
198 hardware_status_subscription_ = cros_settings_->AddSettingsObserver(
199 chromeos::kReportDeviceHardwareStatus, callback);
200 session_status_subscription_ = cros_settings_->AddSettingsObserver(
201 chromeos::kReportDeviceSessionStatus, callback);
203 // The last known location is persisted in local state. This makes location
204 // information available immediately upon startup and avoids the need to
205 // reacquire the location on every user session change or browser crash.
206 content::Geoposition position;
207 std::string timestamp_str;
208 int64 timestamp;
209 const base::DictionaryValue* location =
210 local_state_->GetDictionary(prefs::kDeviceLocation);
211 if (location->GetDouble(kLatitude, &position.latitude) &&
212 location->GetDouble(kLongitude, &position.longitude) &&
213 location->GetDouble(kAltitude, &position.altitude) &&
214 location->GetDouble(kAccuracy, &position.accuracy) &&
215 location->GetDouble(kAltitudeAccuracy, &position.altitude_accuracy) &&
216 location->GetDouble(kHeading, &position.heading) &&
217 location->GetDouble(kSpeed, &position.speed) &&
218 location->GetString(kTimestamp, &timestamp_str) &&
219 base::StringToInt64(timestamp_str, &timestamp)) {
220 position.timestamp = Time::FromInternalValue(timestamp);
221 position_ = position;
224 // Fetch the current values of the policies.
225 UpdateReportingSettings();
227 // Get the the OS and firmware version info.
228 base::PostTaskAndReplyWithResult(
229 content::BrowserThread::GetBlockingPool(),
230 FROM_HERE,
231 base::Bind(&chromeos::version_loader::GetVersion,
232 chromeos::version_loader::VERSION_FULL),
233 base::Bind(&DeviceStatusCollector::OnOSVersion,
234 weak_factory_.GetWeakPtr()));
235 base::PostTaskAndReplyWithResult(
236 content::BrowserThread::GetBlockingPool(),
237 FROM_HERE,
238 base::Bind(&chromeos::version_loader::GetFirmware),
239 base::Bind(&DeviceStatusCollector::OnOSFirmware,
240 weak_factory_.GetWeakPtr()));
243 DeviceStatusCollector::~DeviceStatusCollector() {
246 // static
247 void DeviceStatusCollector::RegisterPrefs(PrefRegistrySimple* registry) {
248 registry->RegisterDictionaryPref(prefs::kDeviceActivityTimes,
249 new base::DictionaryValue);
250 registry->RegisterDictionaryPref(prefs::kDeviceLocation,
251 new base::DictionaryValue);
254 void DeviceStatusCollector::CheckIdleState() {
255 CalculateIdleState(kIdleStateThresholdSeconds,
256 base::Bind(&DeviceStatusCollector::IdleStateCallback,
257 base::Unretained(this)));
260 void DeviceStatusCollector::UpdateReportingSettings() {
261 // Attempt to fetch the current value of the reporting settings.
262 // If trusted values are not available, register this function to be called
263 // back when they are available.
264 if (chromeos::CrosSettingsProvider::TRUSTED !=
265 cros_settings_->PrepareTrustedValues(
266 base::Bind(&DeviceStatusCollector::UpdateReportingSettings,
267 weak_factory_.GetWeakPtr()))) {
268 return;
271 // All reporting settings default to 'enabled'.
272 if (!cros_settings_->GetBoolean(
273 chromeos::kReportDeviceVersionInfo, &report_version_info_)) {
274 report_version_info_ = true;
276 if (!cros_settings_->GetBoolean(
277 chromeos::kReportDeviceActivityTimes, &report_activity_times_)) {
278 report_activity_times_ = true;
280 if (!cros_settings_->GetBoolean(
281 chromeos::kReportDeviceBootMode, &report_boot_mode_)) {
282 report_boot_mode_ = true;
284 if (!cros_settings_->GetBoolean(
285 chromeos::kReportDeviceNetworkInterfaces,
286 &report_network_interfaces_)) {
287 report_network_interfaces_ = true;
289 if (!cros_settings_->GetBoolean(
290 chromeos::kReportDeviceUsers, &report_users_)) {
291 report_users_ = true;
294 const bool already_reporting_hardware_status = report_hardware_status_;
295 if (!cros_settings_->GetBoolean(
296 chromeos::kReportDeviceHardwareStatus, &report_hardware_status_)) {
297 report_hardware_status_ = true;
300 if (!cros_settings_->GetBoolean(
301 chromeos::kReportDeviceSessionStatus, &report_session_status_)) {
302 report_session_status_ = true;
305 // Device location reporting is disabled by default because it is
306 // not launched yet.
307 if (!cros_settings_->GetBoolean(
308 chromeos::kReportDeviceLocation, &report_location_)) {
309 report_location_ = false;
312 if (report_location_) {
313 ScheduleGeolocationUpdateRequest();
314 } else {
315 geolocation_update_timer_.Stop();
316 position_ = content::Geoposition();
317 local_state_->ClearPref(prefs::kDeviceLocation);
320 if (!report_hardware_status_) {
321 ClearCachedHardwareStatus();
322 } else if (!already_reporting_hardware_status) {
323 // Turning on hardware status reporting - fetch an initial sample
324 // immediately instead of waiting for the sampling timer to fire.
325 SampleHardwareStatus();
329 Time DeviceStatusCollector::GetCurrentTime() {
330 return Time::Now();
333 // Remove all out-of-range activity times from the local store.
334 void DeviceStatusCollector::PruneStoredActivityPeriods(Time base_time) {
335 Time min_time =
336 base_time - TimeDelta::FromDays(max_stored_past_activity_days_);
337 Time max_time =
338 base_time + TimeDelta::FromDays(max_stored_future_activity_days_);
339 TrimStoredActivityPeriods(TimestampToDayKey(min_time), 0,
340 TimestampToDayKey(max_time));
343 void DeviceStatusCollector::TrimStoredActivityPeriods(int64 min_day_key,
344 int min_day_trim_duration,
345 int64 max_day_key) {
346 const base::DictionaryValue* activity_times =
347 local_state_->GetDictionary(prefs::kDeviceActivityTimes);
349 scoped_ptr<base::DictionaryValue> copy(activity_times->DeepCopy());
350 for (base::DictionaryValue::Iterator it(*activity_times); !it.IsAtEnd();
351 it.Advance()) {
352 int64 timestamp;
353 if (base::StringToInt64(it.key(), &timestamp)) {
354 // Remove data that is too old, or too far in the future.
355 if (timestamp >= min_day_key && timestamp < max_day_key) {
356 if (timestamp == min_day_key) {
357 int new_activity_duration = 0;
358 if (it.value().GetAsInteger(&new_activity_duration)) {
359 new_activity_duration =
360 std::max(new_activity_duration - min_day_trim_duration, 0);
362 copy->SetInteger(it.key(), new_activity_duration);
364 continue;
367 // The entry is out of range or couldn't be parsed. Remove it.
368 copy->Remove(it.key(), NULL);
370 local_state_->Set(prefs::kDeviceActivityTimes, *copy);
373 void DeviceStatusCollector::AddActivePeriod(Time start, Time end) {
374 DCHECK(start < end);
376 // Maintain the list of active periods in a local_state pref.
377 DictionaryPrefUpdate update(local_state_, prefs::kDeviceActivityTimes);
378 base::DictionaryValue* activity_times = update.Get();
380 // Assign the period to day buckets in local time.
381 Time midnight = start.LocalMidnight();
382 while (midnight < end) {
383 midnight += TimeDelta::FromDays(1);
384 int64 activity = (std::min(end, midnight) - start).InMilliseconds();
385 std::string day_key = base::Int64ToString(TimestampToDayKey(start));
386 int previous_activity = 0;
387 activity_times->GetInteger(day_key, &previous_activity);
388 activity_times->SetInteger(day_key, previous_activity + activity);
389 start = midnight;
393 void DeviceStatusCollector::ClearCachedHardwareStatus() {
394 volume_info_.clear();
395 resource_usage_.clear();
398 void DeviceStatusCollector::IdleStateCallback(ui::IdleState state) {
399 // Do nothing if device activity reporting is disabled.
400 if (!report_activity_times_)
401 return;
403 Time now = GetCurrentTime();
405 if (state == ui::IDLE_STATE_ACTIVE) {
406 // If it's been too long since the last report, or if the activity is
407 // negative (which can happen when the clock changes), assume a single
408 // interval of activity.
409 int active_seconds = (now - last_idle_check_).InSeconds();
410 if (active_seconds < 0 ||
411 active_seconds >= static_cast<int>((2 * kIdlePollIntervalSeconds))) {
412 AddActivePeriod(now - TimeDelta::FromSeconds(kIdlePollIntervalSeconds),
413 now);
414 } else {
415 AddActivePeriod(last_idle_check_, now);
418 PruneStoredActivityPeriods(now);
420 last_idle_check_ = now;
423 scoped_ptr<DeviceLocalAccount>
424 DeviceStatusCollector::GetAutoLaunchedKioskSessionInfo() {
425 scoped_ptr<DeviceLocalAccount> account =
426 GetCurrentKioskDeviceLocalAccount(cros_settings_);
427 if (account) {
428 chromeos::KioskAppManager::App current_app;
429 if (chromeos::KioskAppManager::Get()->GetApp(account->kiosk_app_id,
430 &current_app) &&
431 current_app.was_auto_launched_with_zero_delay) {
432 return account.Pass();
435 // No auto-launched kiosk session active.
436 return scoped_ptr<DeviceLocalAccount>();
439 void DeviceStatusCollector::SampleHardwareStatus() {
440 // If hardware reporting has been disabled, do nothing here.
441 if (!report_hardware_status_)
442 return;
444 // Create list of mounted disk volumes to query status.
445 std::vector<std::string> mount_points;
446 for (const auto& mount_info :
447 chromeos::disks::DiskMountManager::GetInstance()->mount_points()) {
448 // Extract a list of mount points to populate.
449 mount_points.push_back(mount_info.first);
452 // Call out to the blocking pool to measure disk usage.
453 base::PostTaskAndReplyWithResult(
454 content::BrowserThread::GetBlockingPool(),
455 FROM_HERE,
456 base::Bind(volume_info_fetcher_, mount_points),
457 base::Bind(&DeviceStatusCollector::ReceiveVolumeInfo,
458 weak_factory_.GetWeakPtr()));
460 SampleResourceUsage();
463 void DeviceStatusCollector::SampleResourceUsage() {
464 // Walk the process list and measure CPU utilization.
465 double total_usage = 0;
466 std::vector<double> per_process_usage = GetPerProcessCPUUsage();
467 for (double cpu_usage : per_process_usage) {
468 total_usage += cpu_usage;
471 ResourceUsage usage = { total_usage,
472 base::SysInfo::AmountOfAvailablePhysicalMemory() };
474 resource_usage_.push_back(usage);
476 // If our cache of samples is full, throw out old samples to make room for new
477 // sample.
478 if (resource_usage_.size() > kMaxResourceUsageSamples)
479 resource_usage_.pop_front();
482 std::vector<double> DeviceStatusCollector::GetPerProcessCPUUsage() {
483 std::vector<double> cpu_usage;
484 base::ProcessIterator process_iter(nullptr);
486 const int num_processors = base::SysInfo::NumberOfProcessors();
487 while (const base::ProcessEntry* process_entry =
488 process_iter.NextProcessEntry()) {
489 base::Process process = base::Process::Open(process_entry->pid());
490 if (!process.IsValid()) {
491 LOG(ERROR) << "Could not create process handle for process "
492 << process_entry->pid();
493 continue;
495 scoped_ptr<base::ProcessMetrics> metrics(
496 base::ProcessMetrics::CreateProcessMetrics(process.Handle()));
497 const double usage = metrics->GetPlatformIndependentCPUUsage();
498 DCHECK_LE(0, usage);
499 if (usage > 0) {
500 // Convert CPU usage from "percentage of a single core" to "percentage of
501 // all CPU available".
502 cpu_usage.push_back(usage / num_processors);
505 return cpu_usage;
508 void DeviceStatusCollector::GetActivityTimes(
509 em::DeviceStatusReportRequest* request) {
510 DictionaryPrefUpdate update(local_state_, prefs::kDeviceActivityTimes);
511 base::DictionaryValue* activity_times = update.Get();
513 for (base::DictionaryValue::Iterator it(*activity_times); !it.IsAtEnd();
514 it.Advance()) {
515 int64 start_timestamp;
516 int activity_milliseconds;
517 if (base::StringToInt64(it.key(), &start_timestamp) &&
518 it.value().GetAsInteger(&activity_milliseconds)) {
519 // This is correct even when there are leap seconds, because when a leap
520 // second occurs, two consecutive seconds have the same timestamp.
521 int64 end_timestamp = start_timestamp + kMillisecondsPerDay;
523 em::ActiveTimePeriod* active_period = request->add_active_period();
524 em::TimePeriod* period = active_period->mutable_time_period();
525 period->set_start_timestamp(start_timestamp);
526 period->set_end_timestamp(end_timestamp);
527 active_period->set_active_duration(activity_milliseconds);
528 if (start_timestamp >= last_reported_day_) {
529 last_reported_day_ = start_timestamp;
530 duration_for_last_reported_day_ = activity_milliseconds;
532 } else {
533 NOTREACHED();
538 void DeviceStatusCollector::GetVersionInfo(
539 em::DeviceStatusReportRequest* request) {
540 chrome::VersionInfo version_info;
541 request->set_browser_version(version_info.Version());
542 request->set_os_version(os_version_);
543 request->set_firmware_version(firmware_version_);
546 void DeviceStatusCollector::GetBootMode(
547 em::DeviceStatusReportRequest* request) {
548 std::string dev_switch_mode;
549 if (statistics_provider_->GetMachineStatistic(
550 chromeos::system::kDevSwitchBootKey, &dev_switch_mode)) {
551 if (dev_switch_mode == chromeos::system::kDevSwitchBootValueDev)
552 request->set_boot_mode("Dev");
553 else if (dev_switch_mode == chromeos::system::kDevSwitchBootValueVerified)
554 request->set_boot_mode("Verified");
558 void DeviceStatusCollector::GetLocation(
559 em::DeviceStatusReportRequest* request) {
560 em::DeviceLocation* location = request->mutable_device_location();
561 if (!position_.Validate()) {
562 location->set_error_code(
563 em::DeviceLocation::ERROR_CODE_POSITION_UNAVAILABLE);
564 location->set_error_message(position_.error_message);
565 } else {
566 location->set_latitude(position_.latitude);
567 location->set_longitude(position_.longitude);
568 location->set_accuracy(position_.accuracy);
569 location->set_timestamp(
570 (position_.timestamp - Time::UnixEpoch()).InMilliseconds());
571 // Lowest point on land is at approximately -400 meters.
572 if (position_.altitude > -10000.)
573 location->set_altitude(position_.altitude);
574 if (position_.altitude_accuracy >= 0.)
575 location->set_altitude_accuracy(position_.altitude_accuracy);
576 if (position_.heading >= 0. && position_.heading <= 360)
577 location->set_heading(position_.heading);
578 if (position_.speed >= 0.)
579 location->set_speed(position_.speed);
580 location->set_error_code(em::DeviceLocation::ERROR_CODE_NONE);
584 void DeviceStatusCollector::GetNetworkInterfaces(
585 em::DeviceStatusReportRequest* request) {
586 // Maps shill device type strings to proto enum constants.
587 static const struct {
588 const char* type_string;
589 em::NetworkInterface::NetworkDeviceType type_constant;
590 } kDeviceTypeMap[] = {
591 { shill::kTypeEthernet, em::NetworkInterface::TYPE_ETHERNET, },
592 { shill::kTypeWifi, em::NetworkInterface::TYPE_WIFI, },
593 { shill::kTypeWimax, em::NetworkInterface::TYPE_WIMAX, },
594 { shill::kTypeBluetooth, em::NetworkInterface::TYPE_BLUETOOTH, },
595 { shill::kTypeCellular, em::NetworkInterface::TYPE_CELLULAR, },
598 // Maps shill device connection status to proto enum constants.
599 static const struct {
600 const char* state_string;
601 em::NetworkState::ConnectionState state_constant;
602 } kConnectionStateMap[] = {
603 { shill::kStateIdle, em::NetworkState::IDLE },
604 { shill::kStateCarrier, em::NetworkState::CARRIER },
605 { shill::kStateAssociation, em::NetworkState::ASSOCIATION },
606 { shill::kStateConfiguration, em::NetworkState::CONFIGURATION },
607 { shill::kStateReady, em::NetworkState::READY },
608 { shill::kStatePortal, em::NetworkState::PORTAL },
609 { shill::kStateOffline, em::NetworkState::OFFLINE },
610 { shill::kStateOnline, em::NetworkState::ONLINE },
611 { shill::kStateDisconnect, em::NetworkState::DISCONNECT },
612 { shill::kStateFailure, em::NetworkState::FAILURE },
613 { shill::kStateActivationFailure,
614 em::NetworkState::ACTIVATION_FAILURE },
617 chromeos::NetworkStateHandler::DeviceStateList device_list;
618 chromeos::NetworkStateHandler* network_state_handler =
619 chromeos::NetworkHandler::Get()->network_state_handler();
620 network_state_handler->GetDeviceList(&device_list);
622 chromeos::NetworkStateHandler::DeviceStateList::const_iterator device;
623 for (device = device_list.begin(); device != device_list.end(); ++device) {
624 // Determine the type enum constant for |device|.
625 size_t type_idx = 0;
626 for (; type_idx < arraysize(kDeviceTypeMap); ++type_idx) {
627 if ((*device)->type() == kDeviceTypeMap[type_idx].type_string)
628 break;
631 // If the type isn't in |kDeviceTypeMap|, the interface is not relevant for
632 // reporting. This filters out VPN devices.
633 if (type_idx >= arraysize(kDeviceTypeMap))
634 continue;
636 em::NetworkInterface* interface = request->add_network_interface();
637 interface->set_type(kDeviceTypeMap[type_idx].type_constant);
638 if (!(*device)->mac_address().empty())
639 interface->set_mac_address((*device)->mac_address());
640 if (!(*device)->meid().empty())
641 interface->set_meid((*device)->meid());
642 if (!(*device)->imei().empty())
643 interface->set_imei((*device)->imei());
644 if (!(*device)->path().empty())
645 interface->set_device_path((*device)->path());
648 // Don't write any network state if we aren't in a kiosk session.
649 if (!GetAutoLaunchedKioskSessionInfo())
650 return;
652 // Walk the various networks and store their state in the status report.
653 chromeos::NetworkStateHandler::NetworkStateList state_list;
654 network_state_handler->GetNetworkListByType(
655 chromeos::NetworkTypePattern::Default(),
656 true, // configured_only
657 false, // visible_only,
658 0, // no limit to number of results
659 &state_list);
661 for (const chromeos::NetworkState* state: state_list) {
662 // Determine the connection state and signal strength for |state|.
663 em::NetworkState::ConnectionState connection_state_enum =
664 em::NetworkState::UNKNOWN;
665 const std::string connection_state_string(state->connection_state());
666 for (size_t i = 0; i < arraysize(kConnectionStateMap); ++i) {
667 if (connection_state_string == kConnectionStateMap[i].state_string) {
668 connection_state_enum = kConnectionStateMap[i].state_constant;
669 break;
673 // Copy fields from NetworkState into the status report.
674 em::NetworkState* proto_state = request->add_network_state();
675 proto_state->set_connection_state(connection_state_enum);
676 proto_state->set_signal_strength(state->signal_strength());
677 if (!state->device_path().empty())
678 proto_state->set_device_path(state->device_path());
680 if (!state->ip_address().empty())
681 proto_state->set_ip_address(state->ip_address());
683 if (!state->gateway().empty())
684 proto_state->set_gateway(state->gateway());
688 void DeviceStatusCollector::GetUsers(em::DeviceStatusReportRequest* request) {
689 policy::BrowserPolicyConnectorChromeOS* connector =
690 g_browser_process->platform_part()->browser_policy_connector_chromeos();
691 const user_manager::UserList& users =
692 user_manager::UserManager::Get()->GetUsers();
693 user_manager::UserList::const_iterator user;
694 for (user = users.begin(); user != users.end(); ++user) {
695 // Only users with gaia accounts (regular) are reported.
696 if (!(*user)->HasGaiaAccount())
697 continue;
699 em::DeviceUser* device_user = request->add_user();
700 const std::string& email = (*user)->email();
701 if (connector->GetUserAffiliation(email) == USER_AFFILIATION_MANAGED) {
702 device_user->set_type(em::DeviceUser::USER_TYPE_MANAGED);
703 device_user->set_email(email);
704 } else {
705 device_user->set_type(em::DeviceUser::USER_TYPE_UNMANAGED);
706 // Do not report the email address of unmanaged users.
711 void DeviceStatusCollector::GetHardwareStatus(
712 em::DeviceStatusReportRequest* status) {
713 // Add volume info.
714 status->clear_volume_info();
715 for (const em::VolumeInfo& info : volume_info_) {
716 *status->add_volume_info() = info;
719 status->set_system_ram_total(base::SysInfo::AmountOfPhysicalMemory());
720 status->clear_system_ram_free();
721 status->clear_cpu_utilization_pct();
722 for (const ResourceUsage& usage : resource_usage_) {
723 status->add_cpu_utilization_pct(usage.cpu_usage_percent);
724 status->add_system_ram_free(usage.bytes_of_ram_free);
728 bool DeviceStatusCollector::GetDeviceStatus(
729 em::DeviceStatusReportRequest* status) {
730 if (report_activity_times_)
731 GetActivityTimes(status);
733 if (report_version_info_)
734 GetVersionInfo(status);
736 if (report_boot_mode_)
737 GetBootMode(status);
739 if (report_location_)
740 GetLocation(status);
742 if (report_network_interfaces_)
743 GetNetworkInterfaces(status);
745 if (report_users_)
746 GetUsers(status);
748 if (report_hardware_status_)
749 GetHardwareStatus(status);
751 return (report_activity_times_ ||
752 report_version_info_ ||
753 report_boot_mode_ ||
754 report_location_ ||
755 report_network_interfaces_ ||
756 report_users_ ||
757 report_hardware_status_);
760 bool DeviceStatusCollector::GetDeviceSessionStatus(
761 em::SessionStatusReportRequest* status) {
762 // Only generate session status reports if session status reporting is
763 // enabled.
764 if (!report_session_status_)
765 return false;
767 scoped_ptr<const DeviceLocalAccount> account =
768 GetAutoLaunchedKioskSessionInfo();
769 // Only generate session status reports if we are in an auto-launched kiosk
770 // session.
771 if (!account)
772 return false;
774 // Get the account ID associated with this user.
775 status->set_device_local_account_id(account->account_id);
776 em::AppStatus* app_status = status->add_installed_apps();
777 app_status->set_app_id(account->kiosk_app_id);
779 // Look up the app and get the version.
780 const std::string app_version = GetAppVersion(account->kiosk_app_id);
781 if (app_version.empty()) {
782 DLOG(ERROR) << "Unable to get version for extension: "
783 << account->kiosk_app_id;
784 } else {
785 app_status->set_extension_version(app_version);
787 return true;
790 std::string DeviceStatusCollector::GetAppVersion(
791 const std::string& kiosk_app_id) {
792 Profile* const profile =
793 chromeos::ProfileHelper::Get()->GetProfileByUser(
794 user_manager::UserManager::Get()->GetActiveUser());
795 const extensions::ExtensionRegistry* const registry =
796 extensions::ExtensionRegistry::Get(profile);
797 const extensions::Extension* const extension = registry->GetExtensionById(
798 kiosk_app_id, extensions::ExtensionRegistry::EVERYTHING);
799 if (!extension)
800 return std::string();
801 return extension->VersionString();
804 void DeviceStatusCollector::OnSubmittedSuccessfully() {
805 TrimStoredActivityPeriods(last_reported_day_, duration_for_last_reported_day_,
806 std::numeric_limits<int64>::max());
809 void DeviceStatusCollector::OnOSVersion(const std::string& version) {
810 os_version_ = version;
813 void DeviceStatusCollector::OnOSFirmware(const std::string& version) {
814 firmware_version_ = version;
817 void DeviceStatusCollector::ScheduleGeolocationUpdateRequest() {
818 if (geolocation_update_timer_.IsRunning() || geolocation_update_in_progress_)
819 return;
821 if (position_.Validate()) {
822 TimeDelta elapsed = GetCurrentTime() - position_.timestamp;
823 TimeDelta interval =
824 TimeDelta::FromSeconds(kGeolocationPollIntervalSeconds);
825 if (elapsed <= interval) {
826 geolocation_update_timer_.Start(
827 FROM_HERE,
828 interval - elapsed,
829 this,
830 &DeviceStatusCollector::ScheduleGeolocationUpdateRequest);
831 return;
835 geolocation_update_in_progress_ = true;
836 if (location_update_requester_.is_null()) {
837 geolocation_subscription_ = content::GeolocationProvider::GetInstance()->
838 AddLocationUpdateCallback(
839 base::Bind(&DeviceStatusCollector::ReceiveGeolocationUpdate,
840 weak_factory_.GetWeakPtr()),
841 true);
842 } else {
843 location_update_requester_.Run(base::Bind(
844 &DeviceStatusCollector::ReceiveGeolocationUpdate,
845 weak_factory_.GetWeakPtr()));
849 void DeviceStatusCollector::ReceiveGeolocationUpdate(
850 const content::Geoposition& position) {
851 geolocation_update_in_progress_ = false;
853 // Ignore update if device location reporting has since been disabled.
854 if (!report_location_)
855 return;
857 if (position.Validate()) {
858 position_ = position;
859 base::DictionaryValue location;
860 location.SetDouble(kLatitude, position.latitude);
861 location.SetDouble(kLongitude, position.longitude);
862 location.SetDouble(kAltitude, position.altitude);
863 location.SetDouble(kAccuracy, position.accuracy);
864 location.SetDouble(kAltitudeAccuracy, position.altitude_accuracy);
865 location.SetDouble(kHeading, position.heading);
866 location.SetDouble(kSpeed, position.speed);
867 location.SetString(kTimestamp,
868 base::Int64ToString(position.timestamp.ToInternalValue()));
869 local_state_->Set(prefs::kDeviceLocation, location);
872 ScheduleGeolocationUpdateRequest();
875 void DeviceStatusCollector::ReceiveVolumeInfo(
876 const std::vector<em::VolumeInfo>& info) {
877 if (report_hardware_status_)
878 volume_info_ = info;
881 } // namespace policy