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