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"
11 #include <sys/statvfs.h>
13 #include "base/bind.h"
14 #include "base/bind_helpers.h"
15 #include "base/files/file_util.h"
16 #include "base/format_macros.h"
17 #include "base/location.h"
18 #include "base/logging.h"
19 #include "base/memory/scoped_ptr.h"
20 #include "base/posix/eintr_wrapper.h"
21 #include "base/prefs/pref_registry_simple.h"
22 #include "base/prefs/pref_service.h"
23 #include "base/prefs/scoped_user_pref_update.h"
24 #include "base/strings/string_number_conversions.h"
25 #include "base/sys_info.h"
26 #include "base/task_runner_util.h"
27 #include "base/values.h"
28 #include "chrome/browser/browser_process.h"
29 #include "chrome/browser/chromeos/app_mode/kiosk_app_manager.h"
30 #include "chrome/browser/chromeos/policy/browser_policy_connector_chromeos.h"
31 #include "chrome/browser/chromeos/policy/device_local_account.h"
32 #include "chrome/browser/chromeos/profiles/profile_helper.h"
33 #include "chrome/browser/chromeos/settings/cros_settings.h"
34 #include "chrome/common/chrome_version_info.h"
35 #include "chrome/common/pref_names.h"
36 #include "chromeos/disks/disk_mount_manager.h"
37 #include "chromeos/network/device_state.h"
38 #include "chromeos/network/network_handler.h"
39 #include "chromeos/network/network_state.h"
40 #include "chromeos/network/network_state_handler.h"
41 #include "chromeos/settings/cros_settings_names.h"
42 #include "chromeos/system/statistics_provider.h"
43 #include "components/policy/core/common/cloud/cloud_policy_constants.h"
44 #include "components/user_manager/user.h"
45 #include "components/user_manager/user_manager.h"
46 #include "components/user_manager/user_type.h"
47 #include "content/public/browser/browser_thread.h"
48 #include "extensions/browser/extension_registry.h"
49 #include "extensions/common/extension.h"
50 #include "policy/proto/device_management_backend.pb.h"
51 #include "storage/browser/fileapi/external_mount_points.h"
52 #include "third_party/cros_system_api/dbus/service_constants.h"
55 using base::TimeDelta
;
57 namespace em
= enterprise_management
;
60 // How many seconds of inactivity triggers the idle state.
61 const int kIdleStateThresholdSeconds
= 300;
63 // How many days in the past to store active periods for.
64 const unsigned int kMaxStoredPastActivityDays
= 30;
66 // How many days in the future to store active periods for.
67 const unsigned int kMaxStoredFutureActivityDays
= 2;
69 // How often, in seconds, to update the device location.
70 const unsigned int kGeolocationPollIntervalSeconds
= 30 * 60;
72 // How often, in seconds, to sample the hardware state.
73 static const unsigned int kHardwareStatusSampleIntervalSeconds
= 120;
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 // The location we read our CPU statistics from.
86 const char kProcStat
[] = "/proc/stat";
88 // Determine the day key (milliseconds since epoch for corresponding day in UTC)
89 // for a given |timestamp|.
90 int64
TimestampToDayKey(Time timestamp
) {
91 Time::Exploded exploded
;
92 timestamp
.LocalMidnight().LocalExplode(&exploded
);
93 return (Time::FromUTCExploded(exploded
) - Time::UnixEpoch()).InMilliseconds();
96 // Helper function (invoked via blocking pool) to fetch information about
98 std::vector
<em::VolumeInfo
> GetVolumeInfo(
99 const std::vector
<std::string
>& mount_points
) {
100 std::vector
<em::VolumeInfo
> result
;
101 for (const std::string
& mount_point
: mount_points
) {
102 struct statvfs stat
= {}; // Zero-clear
103 if (HANDLE_EINTR(statvfs(mount_point
.c_str(), &stat
)) == 0) {
105 info
.set_volume_id(mount_point
);
106 info
.set_storage_total(static_cast<int64_t>(stat
.f_blocks
) *
108 info
.set_storage_free(static_cast<uint64_t>(stat
.f_bavail
) *
110 result
.push_back(info
);
112 LOG(ERROR
) << "Unable to get volume status for " << mount_point
;
118 // Reads the first CPU line from /proc/stat. Returns an empty string if
119 // the cpu data could not be read.
120 // The format of this line from /proc/stat is:
122 // cpu user_time nice_time system_time idle_time
124 // where user_time, nice_time, system_time, and idle_time are all integer
125 // values measured in jiffies from system startup.
126 std::string
ReadCPUStatistics() {
127 std::string contents
;
128 if (base::ReadFileToString(base::FilePath(kProcStat
), &contents
)) {
129 size_t eol
= contents
.find("\n");
130 if (eol
!= std::string::npos
) {
131 std::string line
= contents
.substr(0, eol
);
132 if (line
.compare(0, 4, "cpu ") == 0)
135 // First line should always start with "cpu ".
136 NOTREACHED() << "Could not parse /proc/stat contents: " << contents
;
138 LOG(WARNING
) << "Unable to read CPU statistics from " << kProcStat
;
139 return std::string();
142 // Returns the DeviceLocalAccount associated with the current kiosk session.
143 // Returns null if there is no active kiosk session, or if that kiosk
144 // session has been removed from policy since the session started, in which
145 // case we won't report its status).
146 scoped_ptr
<policy::DeviceLocalAccount
>
147 GetCurrentKioskDeviceLocalAccount(chromeos::CrosSettings
* settings
) {
148 if (!user_manager::UserManager::Get()->IsLoggedInAsKioskApp())
149 return scoped_ptr
<policy::DeviceLocalAccount
>();
150 const user_manager::User
* const user
=
151 user_manager::UserManager::Get()->GetActiveUser();
152 const std::string user_id
= user
->GetUserID();
153 const std::vector
<policy::DeviceLocalAccount
> accounts
=
154 policy::GetDeviceLocalAccounts(settings
);
156 for (const auto& device_local_account
: accounts
) {
157 if (device_local_account
.user_id
== user_id
) {
158 return make_scoped_ptr(
159 new policy::DeviceLocalAccount(device_local_account
)).Pass();
162 LOG(WARNING
) << "Kiosk app not found in list of device-local accounts";
163 return scoped_ptr
<policy::DeviceLocalAccount
>();
170 DeviceStatusCollector::DeviceStatusCollector(
171 PrefService
* local_state
,
172 chromeos::system::StatisticsProvider
* provider
,
173 const LocationUpdateRequester
& location_update_requester
,
174 const VolumeInfoFetcher
& volume_info_fetcher
,
175 const CPUStatisticsFetcher
& cpu_statistics_fetcher
)
176 : max_stored_past_activity_days_(kMaxStoredPastActivityDays
),
177 max_stored_future_activity_days_(kMaxStoredFutureActivityDays
),
178 local_state_(local_state
),
179 last_idle_check_(Time()),
180 last_reported_day_(0),
181 duration_for_last_reported_day_(0),
182 geolocation_update_in_progress_(false),
183 volume_info_fetcher_(volume_info_fetcher
),
184 cpu_statistics_fetcher_(cpu_statistics_fetcher
),
185 statistics_provider_(provider
),
188 location_update_requester_(location_update_requester
),
189 report_version_info_(false),
190 report_activity_times_(false),
191 report_boot_mode_(false),
192 report_location_(false),
193 report_network_interfaces_(false),
194 report_users_(false),
195 report_hardware_status_(false),
196 report_session_status_(false),
197 weak_factory_(this) {
198 if (volume_info_fetcher_
.is_null())
199 volume_info_fetcher_
= base::Bind(&GetVolumeInfo
);
201 if (cpu_statistics_fetcher_
.is_null())
202 cpu_statistics_fetcher_
= base::Bind(&ReadCPUStatistics
);
204 idle_poll_timer_
.Start(FROM_HERE
,
205 TimeDelta::FromSeconds(kIdlePollIntervalSeconds
),
206 this, &DeviceStatusCollector::CheckIdleState
);
207 hardware_status_sampling_timer_
.Start(
209 TimeDelta::FromSeconds(kHardwareStatusSampleIntervalSeconds
),
210 this, &DeviceStatusCollector::SampleHardwareStatus
);
212 cros_settings_
= chromeos::CrosSettings::Get();
215 // Watch for changes to the individual policies that control what the status
217 base::Closure callback
=
218 base::Bind(&DeviceStatusCollector::UpdateReportingSettings
,
219 base::Unretained(this));
220 version_info_subscription_
= cros_settings_
->AddSettingsObserver(
221 chromeos::kReportDeviceVersionInfo
, callback
);
222 activity_times_subscription_
= cros_settings_
->AddSettingsObserver(
223 chromeos::kReportDeviceActivityTimes
, callback
);
224 boot_mode_subscription_
= cros_settings_
->AddSettingsObserver(
225 chromeos::kReportDeviceBootMode
, callback
);
226 location_subscription_
= cros_settings_
->AddSettingsObserver(
227 chromeos::kReportDeviceLocation
, callback
);
228 network_interfaces_subscription_
= cros_settings_
->AddSettingsObserver(
229 chromeos::kReportDeviceNetworkInterfaces
, callback
);
230 users_subscription_
= cros_settings_
->AddSettingsObserver(
231 chromeos::kReportDeviceUsers
, callback
);
232 hardware_status_subscription_
= cros_settings_
->AddSettingsObserver(
233 chromeos::kReportDeviceHardwareStatus
, callback
);
234 session_status_subscription_
= cros_settings_
->AddSettingsObserver(
235 chromeos::kReportDeviceSessionStatus
, callback
);
237 // The last known location is persisted in local state. This makes location
238 // information available immediately upon startup and avoids the need to
239 // reacquire the location on every user session change or browser crash.
240 content::Geoposition position
;
241 std::string timestamp_str
;
243 const base::DictionaryValue
* location
=
244 local_state_
->GetDictionary(prefs::kDeviceLocation
);
245 if (location
->GetDouble(kLatitude
, &position
.latitude
) &&
246 location
->GetDouble(kLongitude
, &position
.longitude
) &&
247 location
->GetDouble(kAltitude
, &position
.altitude
) &&
248 location
->GetDouble(kAccuracy
, &position
.accuracy
) &&
249 location
->GetDouble(kAltitudeAccuracy
, &position
.altitude_accuracy
) &&
250 location
->GetDouble(kHeading
, &position
.heading
) &&
251 location
->GetDouble(kSpeed
, &position
.speed
) &&
252 location
->GetString(kTimestamp
, ×tamp_str
) &&
253 base::StringToInt64(timestamp_str
, ×tamp
)) {
254 position
.timestamp
= Time::FromInternalValue(timestamp
);
255 position_
= position
;
258 // Fetch the current values of the policies.
259 UpdateReportingSettings();
261 // Get the the OS and firmware version info.
262 base::PostTaskAndReplyWithResult(
263 content::BrowserThread::GetBlockingPool(),
265 base::Bind(&chromeos::version_loader::GetVersion
,
266 chromeos::version_loader::VERSION_FULL
),
267 base::Bind(&DeviceStatusCollector::OnOSVersion
,
268 weak_factory_
.GetWeakPtr()));
269 base::PostTaskAndReplyWithResult(
270 content::BrowserThread::GetBlockingPool(),
272 base::Bind(&chromeos::version_loader::GetFirmware
),
273 base::Bind(&DeviceStatusCollector::OnOSFirmware
,
274 weak_factory_
.GetWeakPtr()));
277 DeviceStatusCollector::~DeviceStatusCollector() {
281 void DeviceStatusCollector::RegisterPrefs(PrefRegistrySimple
* registry
) {
282 registry
->RegisterDictionaryPref(prefs::kDeviceActivityTimes
,
283 new base::DictionaryValue
);
284 registry
->RegisterDictionaryPref(prefs::kDeviceLocation
,
285 new base::DictionaryValue
);
288 void DeviceStatusCollector::CheckIdleState() {
289 CalculateIdleState(kIdleStateThresholdSeconds
,
290 base::Bind(&DeviceStatusCollector::IdleStateCallback
,
291 base::Unretained(this)));
294 void DeviceStatusCollector::UpdateReportingSettings() {
295 // Attempt to fetch the current value of the reporting settings.
296 // If trusted values are not available, register this function to be called
297 // back when they are available.
298 if (chromeos::CrosSettingsProvider::TRUSTED
!=
299 cros_settings_
->PrepareTrustedValues(
300 base::Bind(&DeviceStatusCollector::UpdateReportingSettings
,
301 weak_factory_
.GetWeakPtr()))) {
305 // All reporting settings default to 'enabled'.
306 if (!cros_settings_
->GetBoolean(
307 chromeos::kReportDeviceVersionInfo
, &report_version_info_
)) {
308 report_version_info_
= true;
310 if (!cros_settings_
->GetBoolean(
311 chromeos::kReportDeviceActivityTimes
, &report_activity_times_
)) {
312 report_activity_times_
= true;
314 if (!cros_settings_
->GetBoolean(
315 chromeos::kReportDeviceBootMode
, &report_boot_mode_
)) {
316 report_boot_mode_
= true;
318 if (!cros_settings_
->GetBoolean(
319 chromeos::kReportDeviceNetworkInterfaces
,
320 &report_network_interfaces_
)) {
321 report_network_interfaces_
= true;
323 if (!cros_settings_
->GetBoolean(
324 chromeos::kReportDeviceUsers
, &report_users_
)) {
325 report_users_
= true;
328 const bool already_reporting_hardware_status
= report_hardware_status_
;
329 if (!cros_settings_
->GetBoolean(
330 chromeos::kReportDeviceHardwareStatus
, &report_hardware_status_
)) {
331 report_hardware_status_
= true;
334 if (!cros_settings_
->GetBoolean(
335 chromeos::kReportDeviceSessionStatus
, &report_session_status_
)) {
336 report_session_status_
= true;
339 // Device location reporting is disabled by default because it is
341 if (!cros_settings_
->GetBoolean(
342 chromeos::kReportDeviceLocation
, &report_location_
)) {
343 report_location_
= false;
346 if (report_location_
) {
347 ScheduleGeolocationUpdateRequest();
349 geolocation_update_timer_
.Stop();
350 position_
= content::Geoposition();
351 local_state_
->ClearPref(prefs::kDeviceLocation
);
354 if (!report_hardware_status_
) {
355 ClearCachedHardwareStatus();
356 } else if (!already_reporting_hardware_status
) {
357 // Turning on hardware status reporting - fetch an initial sample
358 // immediately instead of waiting for the sampling timer to fire.
359 SampleHardwareStatus();
363 Time
DeviceStatusCollector::GetCurrentTime() {
367 // Remove all out-of-range activity times from the local store.
368 void DeviceStatusCollector::PruneStoredActivityPeriods(Time base_time
) {
370 base_time
- TimeDelta::FromDays(max_stored_past_activity_days_
);
372 base_time
+ TimeDelta::FromDays(max_stored_future_activity_days_
);
373 TrimStoredActivityPeriods(TimestampToDayKey(min_time
), 0,
374 TimestampToDayKey(max_time
));
377 void DeviceStatusCollector::TrimStoredActivityPeriods(int64 min_day_key
,
378 int min_day_trim_duration
,
380 const base::DictionaryValue
* activity_times
=
381 local_state_
->GetDictionary(prefs::kDeviceActivityTimes
);
383 scoped_ptr
<base::DictionaryValue
> copy(activity_times
->DeepCopy());
384 for (base::DictionaryValue::Iterator
it(*activity_times
); !it
.IsAtEnd();
387 if (base::StringToInt64(it
.key(), ×tamp
)) {
388 // Remove data that is too old, or too far in the future.
389 if (timestamp
>= min_day_key
&& timestamp
< max_day_key
) {
390 if (timestamp
== min_day_key
) {
391 int new_activity_duration
= 0;
392 if (it
.value().GetAsInteger(&new_activity_duration
)) {
393 new_activity_duration
=
394 std::max(new_activity_duration
- min_day_trim_duration
, 0);
396 copy
->SetInteger(it
.key(), new_activity_duration
);
401 // The entry is out of range or couldn't be parsed. Remove it.
402 copy
->Remove(it
.key(), NULL
);
404 local_state_
->Set(prefs::kDeviceActivityTimes
, *copy
);
407 void DeviceStatusCollector::AddActivePeriod(Time start
, Time end
) {
410 // Maintain the list of active periods in a local_state pref.
411 DictionaryPrefUpdate
update(local_state_
, prefs::kDeviceActivityTimes
);
412 base::DictionaryValue
* activity_times
= update
.Get();
414 // Assign the period to day buckets in local time.
415 Time midnight
= start
.LocalMidnight();
416 while (midnight
< end
) {
417 midnight
+= TimeDelta::FromDays(1);
418 int64 activity
= (std::min(end
, midnight
) - start
).InMilliseconds();
419 std::string day_key
= base::Int64ToString(TimestampToDayKey(start
));
420 int previous_activity
= 0;
421 activity_times
->GetInteger(day_key
, &previous_activity
);
422 activity_times
->SetInteger(day_key
, previous_activity
+ activity
);
427 void DeviceStatusCollector::ClearCachedHardwareStatus() {
428 volume_info_
.clear();
429 resource_usage_
.clear();
430 last_cpu_active_
= 0;
434 void DeviceStatusCollector::IdleStateCallback(ui::IdleState state
) {
435 // Do nothing if device activity reporting is disabled.
436 if (!report_activity_times_
)
439 Time now
= GetCurrentTime();
441 if (state
== ui::IDLE_STATE_ACTIVE
) {
442 // If it's been too long since the last report, or if the activity is
443 // negative (which can happen when the clock changes), assume a single
444 // interval of activity.
445 int active_seconds
= (now
- last_idle_check_
).InSeconds();
446 if (active_seconds
< 0 ||
447 active_seconds
>= static_cast<int>((2 * kIdlePollIntervalSeconds
))) {
448 AddActivePeriod(now
- TimeDelta::FromSeconds(kIdlePollIntervalSeconds
),
451 AddActivePeriod(last_idle_check_
, now
);
454 PruneStoredActivityPeriods(now
);
456 last_idle_check_
= now
;
459 scoped_ptr
<DeviceLocalAccount
>
460 DeviceStatusCollector::GetAutoLaunchedKioskSessionInfo() {
461 scoped_ptr
<DeviceLocalAccount
> account
=
462 GetCurrentKioskDeviceLocalAccount(cros_settings_
);
464 chromeos::KioskAppManager::App current_app
;
465 if (chromeos::KioskAppManager::Get()->GetApp(account
->kiosk_app_id
,
467 current_app
.was_auto_launched_with_zero_delay
) {
468 return account
.Pass();
471 // No auto-launched kiosk session active.
472 return scoped_ptr
<DeviceLocalAccount
>();
475 void DeviceStatusCollector::SampleHardwareStatus() {
476 // If hardware reporting has been disabled, do nothing here.
477 if (!report_hardware_status_
)
480 // Create list of mounted disk volumes to query status.
481 std::vector
<storage::MountPoints::MountPointInfo
> external_mount_points
;
482 storage::ExternalMountPoints::GetSystemInstance()->AddMountPointInfosTo(
483 &external_mount_points
);
485 std::vector
<std::string
> mount_points
;
486 for (const auto& info
: external_mount_points
)
487 mount_points
.push_back(info
.path
.value());
489 for (const auto& mount_info
:
490 chromeos::disks::DiskMountManager::GetInstance()->mount_points()) {
491 // Extract a list of mount points to populate.
492 mount_points
.push_back(mount_info
.first
);
495 // Call out to the blocking pool to measure disk and CPU usage.
496 base::PostTaskAndReplyWithResult(
497 content::BrowserThread::GetBlockingPool(),
499 base::Bind(volume_info_fetcher_
, mount_points
),
500 base::Bind(&DeviceStatusCollector::ReceiveVolumeInfo
,
501 weak_factory_
.GetWeakPtr()));
503 base::PostTaskAndReplyWithResult(
504 content::BrowserThread::GetBlockingPool(), FROM_HERE
,
505 cpu_statistics_fetcher_
,
506 base::Bind(&DeviceStatusCollector::ReceiveCPUStatistics
,
507 weak_factory_
.GetWeakPtr()));
510 void DeviceStatusCollector::ReceiveCPUStatistics(const std::string
& stats
) {
511 int cpu_usage_percent
= 0;
513 DLOG(WARNING
) << "Unable to read CPU statistics";
515 // Parse the data from /proc/stat, whose format is defined at
516 // https://www.kernel.org/doc/Documentation/filesystems/proc.txt.
518 // The CPU usage values in /proc/stat are measured in the imprecise unit
519 // "jiffies", but we just care about the relative magnitude of "active" vs
520 // "idle" so the exact value of a jiffy is irrelevant.
522 // An example value for this line:
524 // cpu 123 456 789 012 345 678
526 // We only care about the first four numbers: user_time, nice_time,
527 // sys_time, and idle_time.
528 uint64 user
= 0, nice
= 0, system
= 0, idle
= 0;
529 int vals
= sscanf(stats
.c_str(),
530 "cpu %" PRIu64
" %" PRIu64
" %" PRIu64
" %" PRIu64
, &user
,
531 &nice
, &system
, &idle
);
534 // The values returned from /proc/stat are cumulative totals, so calculate
535 // the difference between the last sample and this one.
536 uint64 active
= user
+ nice
+ system
;
537 uint64 total
= active
+ idle
;
538 uint64 last_total
= last_cpu_active_
+ last_cpu_idle_
;
539 DCHECK_GE(active
, last_cpu_active_
);
540 DCHECK_GE(idle
, last_cpu_idle_
);
541 DCHECK_GE(total
, last_total
);
543 if ((total
- last_total
) > 0) {
545 (100 * (active
- last_cpu_active_
)) / (total
- last_total
);
547 last_cpu_active_
= active
;
548 last_cpu_idle_
= idle
;
551 DCHECK_LE(cpu_usage_percent
, 100);
552 ResourceUsage usage
= {cpu_usage_percent
,
553 base::SysInfo::AmountOfAvailablePhysicalMemory()};
555 resource_usage_
.push_back(usage
);
557 // If our cache of samples is full, throw out old samples to make room for new
559 if (resource_usage_
.size() > kMaxResourceUsageSamples
)
560 resource_usage_
.pop_front();
563 void DeviceStatusCollector::GetActivityTimes(
564 em::DeviceStatusReportRequest
* request
) {
565 DictionaryPrefUpdate
update(local_state_
, prefs::kDeviceActivityTimes
);
566 base::DictionaryValue
* activity_times
= update
.Get();
568 for (base::DictionaryValue::Iterator
it(*activity_times
); !it
.IsAtEnd();
570 int64 start_timestamp
;
571 int activity_milliseconds
;
572 if (base::StringToInt64(it
.key(), &start_timestamp
) &&
573 it
.value().GetAsInteger(&activity_milliseconds
)) {
574 // This is correct even when there are leap seconds, because when a leap
575 // second occurs, two consecutive seconds have the same timestamp.
576 int64 end_timestamp
= start_timestamp
+ Time::kMillisecondsPerDay
;
578 em::ActiveTimePeriod
* active_period
= request
->add_active_period();
579 em::TimePeriod
* period
= active_period
->mutable_time_period();
580 period
->set_start_timestamp(start_timestamp
);
581 period
->set_end_timestamp(end_timestamp
);
582 active_period
->set_active_duration(activity_milliseconds
);
583 if (start_timestamp
>= last_reported_day_
) {
584 last_reported_day_
= start_timestamp
;
585 duration_for_last_reported_day_
= activity_milliseconds
;
593 void DeviceStatusCollector::GetVersionInfo(
594 em::DeviceStatusReportRequest
* request
) {
595 chrome::VersionInfo version_info
;
596 request
->set_browser_version(version_info
.Version());
597 request
->set_os_version(os_version_
);
598 request
->set_firmware_version(firmware_version_
);
601 void DeviceStatusCollector::GetBootMode(
602 em::DeviceStatusReportRequest
* request
) {
603 std::string dev_switch_mode
;
604 if (statistics_provider_
->GetMachineStatistic(
605 chromeos::system::kDevSwitchBootKey
, &dev_switch_mode
)) {
606 if (dev_switch_mode
== chromeos::system::kDevSwitchBootValueDev
)
607 request
->set_boot_mode("Dev");
608 else if (dev_switch_mode
== chromeos::system::kDevSwitchBootValueVerified
)
609 request
->set_boot_mode("Verified");
613 void DeviceStatusCollector::GetLocation(
614 em::DeviceStatusReportRequest
* request
) {
615 em::DeviceLocation
* location
= request
->mutable_device_location();
616 if (!position_
.Validate()) {
617 location
->set_error_code(
618 em::DeviceLocation::ERROR_CODE_POSITION_UNAVAILABLE
);
619 location
->set_error_message(position_
.error_message
);
621 location
->set_latitude(position_
.latitude
);
622 location
->set_longitude(position_
.longitude
);
623 location
->set_accuracy(position_
.accuracy
);
624 location
->set_timestamp(
625 (position_
.timestamp
- Time::UnixEpoch()).InMilliseconds());
626 // Lowest point on land is at approximately -400 meters.
627 if (position_
.altitude
> -10000.)
628 location
->set_altitude(position_
.altitude
);
629 if (position_
.altitude_accuracy
>= 0.)
630 location
->set_altitude_accuracy(position_
.altitude_accuracy
);
631 if (position_
.heading
>= 0. && position_
.heading
<= 360)
632 location
->set_heading(position_
.heading
);
633 if (position_
.speed
>= 0.)
634 location
->set_speed(position_
.speed
);
635 location
->set_error_code(em::DeviceLocation::ERROR_CODE_NONE
);
639 int DeviceStatusCollector::ConvertWifiSignalStrength(int signal_strength
) {
640 // Shill attempts to convert WiFi signal strength from its internal dBm to a
641 // percentage range (from 0-100) by adding 120 to the raw dBm value,
642 // and then clamping the result to the range 0-100 (see
643 // shill::WiFiService::SignalToStrength()).
645 // To convert back to dBm, we subtract 120 from the percentage value to yield
646 // a clamped dBm value in the range of -119 to -20dBm.
648 // TODO(atwilson): Tunnel the raw dBm signal strength from Shill instead of
649 // doing the conversion here so we can report non-clamped values
650 // (crbug.com/463334).
651 DCHECK_GT(signal_strength
, 0);
652 DCHECK_LE(signal_strength
, 100);
653 return signal_strength
- 120;
656 void DeviceStatusCollector::GetNetworkInterfaces(
657 em::DeviceStatusReportRequest
* request
) {
658 // Maps shill device type strings to proto enum constants.
659 static const struct {
660 const char* type_string
;
661 em::NetworkInterface::NetworkDeviceType type_constant
;
662 } kDeviceTypeMap
[] = {
663 { shill::kTypeEthernet
, em::NetworkInterface::TYPE_ETHERNET
, },
664 { shill::kTypeWifi
, em::NetworkInterface::TYPE_WIFI
, },
665 { shill::kTypeWimax
, em::NetworkInterface::TYPE_WIMAX
, },
666 { shill::kTypeBluetooth
, em::NetworkInterface::TYPE_BLUETOOTH
, },
667 { shill::kTypeCellular
, em::NetworkInterface::TYPE_CELLULAR
, },
670 // Maps shill device connection status to proto enum constants.
671 static const struct {
672 const char* state_string
;
673 em::NetworkState::ConnectionState state_constant
;
674 } kConnectionStateMap
[] = {
675 { shill::kStateIdle
, em::NetworkState::IDLE
},
676 { shill::kStateCarrier
, em::NetworkState::CARRIER
},
677 { shill::kStateAssociation
, em::NetworkState::ASSOCIATION
},
678 { shill::kStateConfiguration
, em::NetworkState::CONFIGURATION
},
679 { shill::kStateReady
, em::NetworkState::READY
},
680 { shill::kStatePortal
, em::NetworkState::PORTAL
},
681 { shill::kStateOffline
, em::NetworkState::OFFLINE
},
682 { shill::kStateOnline
, em::NetworkState::ONLINE
},
683 { shill::kStateDisconnect
, em::NetworkState::DISCONNECT
},
684 { shill::kStateFailure
, em::NetworkState::FAILURE
},
685 { shill::kStateActivationFailure
,
686 em::NetworkState::ACTIVATION_FAILURE
},
689 chromeos::NetworkStateHandler::DeviceStateList device_list
;
690 chromeos::NetworkStateHandler
* network_state_handler
=
691 chromeos::NetworkHandler::Get()->network_state_handler();
692 network_state_handler
->GetDeviceList(&device_list
);
694 chromeos::NetworkStateHandler::DeviceStateList::const_iterator device
;
695 for (device
= device_list
.begin(); device
!= device_list
.end(); ++device
) {
696 // Determine the type enum constant for |device|.
698 for (; type_idx
< arraysize(kDeviceTypeMap
); ++type_idx
) {
699 if ((*device
)->type() == kDeviceTypeMap
[type_idx
].type_string
)
703 // If the type isn't in |kDeviceTypeMap|, the interface is not relevant for
704 // reporting. This filters out VPN devices.
705 if (type_idx
>= arraysize(kDeviceTypeMap
))
708 em::NetworkInterface
* interface
= request
->add_network_interface();
709 interface
->set_type(kDeviceTypeMap
[type_idx
].type_constant
);
710 if (!(*device
)->mac_address().empty())
711 interface
->set_mac_address((*device
)->mac_address());
712 if (!(*device
)->meid().empty())
713 interface
->set_meid((*device
)->meid());
714 if (!(*device
)->imei().empty())
715 interface
->set_imei((*device
)->imei());
716 if (!(*device
)->path().empty())
717 interface
->set_device_path((*device
)->path());
720 // Don't write any network state if we aren't in a kiosk session.
721 if (!GetAutoLaunchedKioskSessionInfo())
724 // Walk the various networks and store their state in the status report.
725 chromeos::NetworkStateHandler::NetworkStateList state_list
;
726 network_state_handler
->GetNetworkListByType(
727 chromeos::NetworkTypePattern::Default(),
728 true, // configured_only
729 false, // visible_only
730 0, // no limit to number of results
733 for (const chromeos::NetworkState
* state
: state_list
) {
734 // Determine the connection state and signal strength for |state|.
735 em::NetworkState::ConnectionState connection_state_enum
=
736 em::NetworkState::UNKNOWN
;
737 const std::string
connection_state_string(state
->connection_state());
738 for (size_t i
= 0; i
< arraysize(kConnectionStateMap
); ++i
) {
739 if (connection_state_string
== kConnectionStateMap
[i
].state_string
) {
740 connection_state_enum
= kConnectionStateMap
[i
].state_constant
;
745 // Copy fields from NetworkState into the status report.
746 em::NetworkState
* proto_state
= request
->add_network_state();
747 proto_state
->set_connection_state(connection_state_enum
);
749 // Report signal strength for wifi connections.
750 if (state
->type() == shill::kTypeWifi
) {
751 // If shill has provided a signal strength, convert it to dBm and store it
752 // in the status report. A signal_strength() of 0 connotes "no signal"
753 // rather than "really weak signal", so we only report signal strength if
755 if (state
->signal_strength()) {
756 proto_state
->set_signal_strength(
757 ConvertWifiSignalStrength(state
->signal_strength()));
761 if (!state
->device_path().empty())
762 proto_state
->set_device_path(state
->device_path());
764 if (!state
->ip_address().empty())
765 proto_state
->set_ip_address(state
->ip_address());
767 if (!state
->gateway().empty())
768 proto_state
->set_gateway(state
->gateway());
772 void DeviceStatusCollector::GetUsers(em::DeviceStatusReportRequest
* request
) {
773 policy::BrowserPolicyConnectorChromeOS
* connector
=
774 g_browser_process
->platform_part()->browser_policy_connector_chromeos();
775 const user_manager::UserList
& users
=
776 user_manager::UserManager::Get()->GetUsers();
777 user_manager::UserList::const_iterator user
;
778 for (user
= users
.begin(); user
!= users
.end(); ++user
) {
779 // Only users with gaia accounts (regular) are reported.
780 if (!(*user
)->HasGaiaAccount())
783 em::DeviceUser
* device_user
= request
->add_user();
784 const std::string
& email
= (*user
)->email();
785 if (connector
->GetUserAffiliation(email
) == USER_AFFILIATION_MANAGED
) {
786 device_user
->set_type(em::DeviceUser::USER_TYPE_MANAGED
);
787 device_user
->set_email(email
);
789 device_user
->set_type(em::DeviceUser::USER_TYPE_UNMANAGED
);
790 // Do not report the email address of unmanaged users.
795 void DeviceStatusCollector::GetHardwareStatus(
796 em::DeviceStatusReportRequest
* status
) {
798 status
->clear_volume_info();
799 for (const em::VolumeInfo
& info
: volume_info_
) {
800 *status
->add_volume_info() = info
;
803 status
->set_system_ram_total(base::SysInfo::AmountOfPhysicalMemory());
804 status
->clear_system_ram_free();
805 status
->clear_cpu_utilization_pct();
806 for (const ResourceUsage
& usage
: resource_usage_
) {
807 status
->add_cpu_utilization_pct(usage
.cpu_usage_percent
);
808 status
->add_system_ram_free(usage
.bytes_of_ram_free
);
812 bool DeviceStatusCollector::GetDeviceStatus(
813 em::DeviceStatusReportRequest
* status
) {
814 if (report_activity_times_
)
815 GetActivityTimes(status
);
817 if (report_version_info_
)
818 GetVersionInfo(status
);
820 if (report_boot_mode_
)
823 if (report_location_
)
826 if (report_network_interfaces_
)
827 GetNetworkInterfaces(status
);
832 if (report_hardware_status_
)
833 GetHardwareStatus(status
);
835 return (report_activity_times_
||
836 report_version_info_
||
839 report_network_interfaces_
||
841 report_hardware_status_
);
844 bool DeviceStatusCollector::GetDeviceSessionStatus(
845 em::SessionStatusReportRequest
* status
) {
846 // Only generate session status reports if session status reporting is
848 if (!report_session_status_
)
851 scoped_ptr
<const DeviceLocalAccount
> account
=
852 GetAutoLaunchedKioskSessionInfo();
853 // Only generate session status reports if we are in an auto-launched kiosk
858 // Get the account ID associated with this user.
859 status
->set_device_local_account_id(account
->account_id
);
860 em::AppStatus
* app_status
= status
->add_installed_apps();
861 app_status
->set_app_id(account
->kiosk_app_id
);
863 // Look up the app and get the version.
864 const std::string app_version
= GetAppVersion(account
->kiosk_app_id
);
865 if (app_version
.empty()) {
866 DLOG(ERROR
) << "Unable to get version for extension: "
867 << account
->kiosk_app_id
;
869 app_status
->set_extension_version(app_version
);
874 std::string
DeviceStatusCollector::GetAppVersion(
875 const std::string
& kiosk_app_id
) {
876 Profile
* const profile
=
877 chromeos::ProfileHelper::Get()->GetProfileByUser(
878 user_manager::UserManager::Get()->GetActiveUser());
879 const extensions::ExtensionRegistry
* const registry
=
880 extensions::ExtensionRegistry::Get(profile
);
881 const extensions::Extension
* const extension
= registry
->GetExtensionById(
882 kiosk_app_id
, extensions::ExtensionRegistry::EVERYTHING
);
884 return std::string();
885 return extension
->VersionString();
888 void DeviceStatusCollector::OnSubmittedSuccessfully() {
889 TrimStoredActivityPeriods(last_reported_day_
, duration_for_last_reported_day_
,
890 std::numeric_limits
<int64
>::max());
893 void DeviceStatusCollector::OnOSVersion(const std::string
& version
) {
894 os_version_
= version
;
897 void DeviceStatusCollector::OnOSFirmware(const std::string
& version
) {
898 firmware_version_
= version
;
901 void DeviceStatusCollector::ScheduleGeolocationUpdateRequest() {
902 if (geolocation_update_timer_
.IsRunning() || geolocation_update_in_progress_
)
905 if (position_
.Validate()) {
906 TimeDelta elapsed
= GetCurrentTime() - position_
.timestamp
;
908 TimeDelta::FromSeconds(kGeolocationPollIntervalSeconds
);
909 if (elapsed
<= interval
) {
910 geolocation_update_timer_
.Start(
914 &DeviceStatusCollector::ScheduleGeolocationUpdateRequest
);
919 geolocation_update_in_progress_
= true;
920 if (location_update_requester_
.is_null()) {
921 geolocation_subscription_
= content::GeolocationProvider::GetInstance()->
922 AddLocationUpdateCallback(
923 base::Bind(&DeviceStatusCollector::ReceiveGeolocationUpdate
,
924 weak_factory_
.GetWeakPtr()),
927 location_update_requester_
.Run(base::Bind(
928 &DeviceStatusCollector::ReceiveGeolocationUpdate
,
929 weak_factory_
.GetWeakPtr()));
933 void DeviceStatusCollector::ReceiveGeolocationUpdate(
934 const content::Geoposition
& position
) {
935 geolocation_update_in_progress_
= false;
937 // Ignore update if device location reporting has since been disabled.
938 if (!report_location_
)
941 if (position
.Validate()) {
942 position_
= position
;
943 base::DictionaryValue location
;
944 location
.SetDouble(kLatitude
, position
.latitude
);
945 location
.SetDouble(kLongitude
, position
.longitude
);
946 location
.SetDouble(kAltitude
, position
.altitude
);
947 location
.SetDouble(kAccuracy
, position
.accuracy
);
948 location
.SetDouble(kAltitudeAccuracy
, position
.altitude_accuracy
);
949 location
.SetDouble(kHeading
, position
.heading
);
950 location
.SetDouble(kSpeed
, position
.speed
);
951 location
.SetString(kTimestamp
,
952 base::Int64ToString(position
.timestamp
.ToInternalValue()));
953 local_state_
->Set(prefs::kDeviceLocation
, location
);
956 ScheduleGeolocationUpdateRequest();
959 void DeviceStatusCollector::ReceiveVolumeInfo(
960 const std::vector
<em::VolumeInfo
>& info
) {
961 if (report_hardware_status_
)
965 } // namespace policy