device_status_collector.cc revision eb525c5499e34cc9c4b825d6d9e75bb07cc06ace
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_notification_types.h"
24#include "chrome/common/chrome_version_info.h"
25#include "chrome/common/pref_names.h"
26#include "content/public/browser/browser_thread.h"
27#include "content/public/browser/notification_details.h"
28#include "content/public/browser/notification_source.h"
29
30using base::Time;
31using base::TimeDelta;
32using chromeos::VersionLoader;
33
34namespace em = enterprise_management;
35
36namespace {
37// How many seconds of inactivity triggers the idle state.
38const int kIdleStateThresholdSeconds = 300;
39
40// How many days in the past to store active periods for.
41const unsigned int kMaxStoredPastActivityDays = 30;
42
43// How many days in the future to store active periods for.
44const unsigned int kMaxStoredFutureActivityDays = 2;
45
46// How often, in seconds, to update the device location.
47const unsigned int kGeolocationPollIntervalSeconds = 30 * 60;
48
49const int64 kMillisecondsPerDay = Time::kMicrosecondsPerDay / 1000;
50
51const char kLatitude[] = "latitude";
52
53const char kLongitude[] = "longitude";
54
55const char kAltitude[] = "altitude";
56
57const char kAccuracy[] = "accuracy";
58
59const char kAltitudeAccuracy[] = "altitude_accuracy";
60
61const char kHeading[] = "heading";
62
63const char kSpeed[] = "speed";
64
65const char kTimestamp[] = "timestamp";
66
67// Determine the day key (milliseconds since epoch for corresponding day in UTC)
68// for a given |timestamp|.
69int64 TimestampToDayKey(Time timestamp) {
70  Time::Exploded exploded;
71  timestamp.LocalMidnight().LocalExplode(&exploded);
72  return (Time::FromUTCExploded(exploded) - Time::UnixEpoch()).InMilliseconds();
73}
74
75}  // namespace
76
77namespace policy {
78
79DeviceStatusCollector::Context::Context() {
80}
81
82DeviceStatusCollector::Context::~Context() {
83}
84
85void DeviceStatusCollector::Context::GetLocationUpdate(
86    const content::GeolocationProvider::LocationUpdateCallback& callback) {
87  owner_callback_ = callback;
88  content::BrowserThread::PostTask(
89      content::BrowserThread::IO,
90      FROM_HERE,
91      base::Bind(&DeviceStatusCollector::Context::GetLocationUpdateInternal,
92                 this));
93}
94
95void DeviceStatusCollector::Context::GetLocationUpdateInternal() {
96  our_callback_ = base::Bind(
97      &DeviceStatusCollector::Context::OnLocationUpdate, this);
98  content::GeolocationProvider::GetInstance()->AddLocationUpdateCallback(
99      our_callback_, true);
100}
101
102void DeviceStatusCollector::Context::OnLocationUpdate(
103    const content::Geoposition& geoposition) {
104  content::GeolocationProvider::GetInstance()->RemoveLocationUpdateCallback(
105      our_callback_);
106  our_callback_.Reset();
107  content::BrowserThread::PostTask(
108      content::BrowserThread::UI,
109      FROM_HERE,
110      base::Bind(&DeviceStatusCollector::Context::CallCollector,
111                 this, geoposition));
112}
113
114void DeviceStatusCollector::Context::CallCollector(
115    const content::Geoposition& geoposition) {
116  owner_callback_.Run(geoposition);
117  owner_callback_.Reset();
118}
119
120DeviceStatusCollector::DeviceStatusCollector(
121    PrefService* local_state,
122    chromeos::system::StatisticsProvider* provider,
123    LocationUpdateRequester* location_update_requester)
124    : max_stored_past_activity_days_(kMaxStoredPastActivityDays),
125      max_stored_future_activity_days_(kMaxStoredFutureActivityDays),
126      local_state_(local_state),
127      last_idle_check_(Time()),
128      last_reported_day_(0),
129      duration_for_last_reported_day_(0),
130      geolocation_update_in_progress_(false),
131      statistics_provider_(provider),
132      weak_factory_(this),
133      report_version_info_(false),
134      report_activity_times_(false),
135      report_boot_mode_(false),
136      report_location_(false),
137      context_(new Context()) {
138  if (location_update_requester) {
139    location_update_requester_ = *location_update_requester;
140  } else {
141    location_update_requester_ =
142        base::Bind(&Context::GetLocationUpdate, context_.get());
143  }
144  idle_poll_timer_.Start(FROM_HERE,
145                         TimeDelta::FromSeconds(kIdlePollIntervalSeconds),
146                         this, &DeviceStatusCollector::CheckIdleState);
147
148  cros_settings_ = chromeos::CrosSettings::Get();
149
150  // Watch for changes to the individual policies that control what the status
151  // reports contain.
152  cros_settings_->AddSettingsObserver(chromeos::kReportDeviceVersionInfo, this);
153  cros_settings_->AddSettingsObserver(chromeos::kReportDeviceActivityTimes,
154                                      this);
155  cros_settings_->AddSettingsObserver(chromeos::kReportDeviceBootMode, this);
156  cros_settings_->AddSettingsObserver(chromeos::kReportDeviceLocation, this);
157
158  // The last known location is persisted in local state. This makes location
159  // information available immediately upon startup and avoids the need to
160  // reacquire the location on every user session change or browser crash.
161  content::Geoposition position;
162  std::string timestamp_str;
163  int64 timestamp;
164  const base::DictionaryValue* location =
165      local_state_->GetDictionary(prefs::kDeviceLocation);
166  if (location->GetDouble(kLatitude, &position.latitude) &&
167      location->GetDouble(kLongitude, &position.longitude) &&
168      location->GetDouble(kAltitude, &position.altitude) &&
169      location->GetDouble(kAccuracy, &position.accuracy) &&
170      location->GetDouble(kAltitudeAccuracy, &position.altitude_accuracy) &&
171      location->GetDouble(kHeading, &position.heading) &&
172      location->GetDouble(kSpeed, &position.speed) &&
173      location->GetString(kTimestamp, &timestamp_str) &&
174      base::StringToInt64(timestamp_str, &timestamp)) {
175    position.timestamp = Time::FromInternalValue(timestamp);
176    position_ = position;
177  }
178
179  // Fetch the current values of the policies.
180  UpdateReportingSettings();
181
182  // Get the the OS and firmware version info.
183  version_loader_.GetVersion(
184      VersionLoader::VERSION_FULL,
185      base::Bind(&DeviceStatusCollector::OnOSVersion, base::Unretained(this)),
186      &tracker_);
187  version_loader_.GetFirmware(
188      base::Bind(&DeviceStatusCollector::OnOSFirmware, base::Unretained(this)),
189      &tracker_);
190}
191
192DeviceStatusCollector::~DeviceStatusCollector() {
193  cros_settings_->RemoveSettingsObserver(chromeos::kReportDeviceVersionInfo,
194                                         this);
195  cros_settings_->RemoveSettingsObserver(chromeos::kReportDeviceActivityTimes,
196                                         this);
197  cros_settings_->RemoveSettingsObserver(chromeos::kReportDeviceBootMode, this);
198  cros_settings_->RemoveSettingsObserver(chromeos::kReportDeviceLocation, this);
199}
200
201// static
202void DeviceStatusCollector::RegisterPrefs(PrefRegistrySimple* registry) {
203  registry->RegisterDictionaryPref(prefs::kDeviceActivityTimes,
204                                   new base::DictionaryValue);
205  registry->RegisterDictionaryPref(prefs::kDeviceLocation,
206                                   new base::DictionaryValue);
207}
208
209void DeviceStatusCollector::CheckIdleState() {
210  CalculateIdleState(kIdleStateThresholdSeconds,
211      base::Bind(&DeviceStatusCollector::IdleStateCallback,
212                 base::Unretained(this)));
213}
214
215void DeviceStatusCollector::UpdateReportingSettings() {
216  // Attempt to fetch the current value of the reporting settings.
217  // If trusted values are not available, register this function to be called
218  // back when they are available.
219  if (chromeos::CrosSettingsProvider::TRUSTED !=
220      cros_settings_->PrepareTrustedValues(
221      base::Bind(&DeviceStatusCollector::UpdateReportingSettings,
222                 weak_factory_.GetWeakPtr()))) {
223    return;
224  }
225  cros_settings_->GetBoolean(
226      chromeos::kReportDeviceVersionInfo, &report_version_info_);
227  cros_settings_->GetBoolean(
228      chromeos::kReportDeviceActivityTimes, &report_activity_times_);
229  cros_settings_->GetBoolean(
230      chromeos::kReportDeviceBootMode, &report_boot_mode_);
231  cros_settings_->GetBoolean(
232      chromeos::kReportDeviceLocation, &report_location_);
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::GetStatus(em::DeviceStatusReportRequest* request) {
409  // TODO(mnissler): Remove once the old cloud policy stack is retired. The old
410  // stack doesn't support reporting successful submissions back to here, so
411  // just assume whatever ends up in |request| gets submitted successfully.
412  GetDeviceStatus(request);
413  OnSubmittedSuccessfully();
414}
415
416bool DeviceStatusCollector::GetDeviceStatus(
417    em::DeviceStatusReportRequest* status) {
418  if (report_activity_times_)
419    GetActivityTimes(status);
420
421  if (report_version_info_)
422    GetVersionInfo(status);
423
424  if (report_boot_mode_)
425    GetBootMode(status);
426
427  if (report_location_)
428    GetLocation(status);
429
430  return true;
431}
432
433bool DeviceStatusCollector::GetSessionStatus(
434    em::SessionStatusReportRequest* status) {
435  return false;
436}
437
438void DeviceStatusCollector::OnSubmittedSuccessfully() {
439  TrimStoredActivityPeriods(last_reported_day_, duration_for_last_reported_day_,
440                            std::numeric_limits<int64>::max());
441}
442
443void DeviceStatusCollector::OnOSVersion(const std::string& version) {
444  os_version_ = version;
445}
446
447void DeviceStatusCollector::OnOSFirmware(const std::string& version) {
448  firmware_version_ = version;
449}
450
451void DeviceStatusCollector::Observe(
452    int type,
453    const content::NotificationSource& source,
454    const content::NotificationDetails& details) {
455  if (type == chrome::NOTIFICATION_SYSTEM_SETTING_CHANGED)
456    UpdateReportingSettings();
457  else
458    NOTREACHED();
459}
460
461void DeviceStatusCollector::ScheduleGeolocationUpdateRequest() {
462  if (geolocation_update_timer_.IsRunning() || geolocation_update_in_progress_)
463    return;
464
465  if (position_.Validate()) {
466    TimeDelta elapsed = GetCurrentTime() - position_.timestamp;
467    TimeDelta interval =
468        TimeDelta::FromSeconds(kGeolocationPollIntervalSeconds);
469    if (elapsed > interval) {
470      geolocation_update_in_progress_ = true;
471      location_update_requester_.Run(base::Bind(
472          &DeviceStatusCollector::ReceiveGeolocationUpdate,
473          weak_factory_.GetWeakPtr()));
474    } else {
475      geolocation_update_timer_.Start(
476          FROM_HERE,
477          interval - elapsed,
478          this,
479          &DeviceStatusCollector::ScheduleGeolocationUpdateRequest);
480    }
481  } else {
482    geolocation_update_in_progress_ = true;
483    location_update_requester_.Run(base::Bind(
484        &DeviceStatusCollector::ReceiveGeolocationUpdate,
485        weak_factory_.GetWeakPtr()));
486  }
487}
488
489void DeviceStatusCollector::ReceiveGeolocationUpdate(
490    const content::Geoposition& position) {
491  geolocation_update_in_progress_ = false;
492
493  // Ignore update if device location reporting has since been disabled.
494  if (!report_location_)
495    return;
496
497  if (position.Validate()) {
498    position_ = position;
499    base::DictionaryValue location;
500    location.SetDouble(kLatitude, position.latitude);
501    location.SetDouble(kLongitude, position.longitude);
502    location.SetDouble(kAltitude, position.altitude);
503    location.SetDouble(kAccuracy, position.accuracy);
504    location.SetDouble(kAltitudeAccuracy, position.altitude_accuracy);
505    location.SetDouble(kHeading, position.heading);
506    location.SetDouble(kSpeed, position.speed);
507    location.SetString(kTimestamp,
508        base::Int64ToString(position.timestamp.ToInternalValue()));
509    local_state_->Set(prefs::kDeviceLocation, location);
510  }
511
512  ScheduleGeolocationUpdateRequest();
513}
514
515}  // namespace policy
516