1 // Copyright 2014 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 "components/metrics/metrics_state_manager.h"
7 #include "base/command_line.h"
9 #include "base/metrics/histogram.h"
10 #include "base/metrics/sparse_histogram.h"
11 #include "base/prefs/pref_registry_simple.h"
12 #include "base/prefs/pref_service.h"
13 #include "base/rand_util.h"
14 #include "base/strings/string_number_conversions.h"
15 #include "base/threading/thread_restrictions.h"
16 #include "base/time/time.h"
17 #include "components/metrics/cloned_install_detector.h"
18 #include "components/metrics/machine_id_provider.h"
19 #include "components/metrics/metrics_pref_names.h"
20 #include "components/metrics/metrics_switches.h"
21 #include "components/variations/caching_permuted_entropy_provider.h"
27 // The argument used to generate a non-identifying entropy source. We want no
28 // more than 13 bits of entropy, so use this max to return a number in the range
29 // [0, 7999] as the entropy source (12.97 bits of entropy).
30 const int kMaxLowEntropySize
= 8000;
32 // Default prefs value for prefs::kMetricsLowEntropySource to indicate that
33 // the value has not yet been set.
34 const int kLowEntropySourceNotSet
= -1;
36 // Generates a new non-identifying entropy source used to seed persistent
38 int GenerateLowEntropySource() {
39 return base::RandInt(0, kMaxLowEntropySize
- 1);
45 bool MetricsStateManager::instance_exists_
= false;
47 MetricsStateManager::MetricsStateManager(
48 PrefService
* local_state
,
49 const base::Callback
<bool(void)>& is_reporting_enabled_callback
,
50 const StoreClientInfoCallback
& store_client_info
,
51 const LoadClientInfoCallback
& retrieve_client_info
)
52 : local_state_(local_state
),
53 is_reporting_enabled_callback_(is_reporting_enabled_callback
),
54 store_client_info_(store_client_info
),
55 load_client_info_(retrieve_client_info
),
56 low_entropy_source_(kLowEntropySourceNotSet
),
57 entropy_source_returned_(ENTROPY_SOURCE_NONE
) {
58 ResetMetricsIDsIfNecessary();
59 if (IsMetricsReportingEnabled())
60 ForceClientIdCreation();
62 DCHECK(!instance_exists_
);
63 instance_exists_
= true;
66 MetricsStateManager::~MetricsStateManager() {
67 DCHECK(instance_exists_
);
68 instance_exists_
= false;
71 bool MetricsStateManager::IsMetricsReportingEnabled() {
72 return is_reporting_enabled_callback_
.Run();
75 void MetricsStateManager::ForceClientIdCreation() {
76 if (!client_id_
.empty())
79 client_id_
= local_state_
->GetString(prefs::kMetricsClientID
);
80 if (!client_id_
.empty()) {
81 // It is technically sufficient to only save a backup of the client id when
82 // it is initially generated below, but since the backup was only introduced
83 // in M38, seed it explicitly from here for some time.
84 BackUpCurrentClientInfo();
88 const scoped_ptr
<ClientInfo
> client_info_backup
=
89 LoadClientInfoAndMaybeMigrate();
90 if (client_info_backup
) {
91 client_id_
= client_info_backup
->client_id
;
93 const base::Time now
= base::Time::Now();
95 // Save the recovered client id and also try to reinstantiate the backup
96 // values for the dates corresponding with that client id in order to avoid
97 // weird scenarios where we could report an old client id with a recent
99 local_state_
->SetString(prefs::kMetricsClientID
, client_id_
);
100 local_state_
->SetInt64(prefs::kInstallDate
,
101 client_info_backup
->installation_date
!= 0
102 ? client_info_backup
->installation_date
104 local_state_
->SetInt64(prefs::kMetricsReportingEnabledTimestamp
,
105 client_info_backup
->reporting_enabled_date
!= 0
106 ? client_info_backup
->reporting_enabled_date
109 base::TimeDelta recovered_installation_age
;
110 if (client_info_backup
->installation_date
!= 0) {
111 recovered_installation_age
=
112 now
- base::Time::FromTimeT(client_info_backup
->installation_date
);
114 UMA_HISTOGRAM_COUNTS_10000("UMA.ClientIdBackupRecoveredWithAge",
115 recovered_installation_age
.InHours());
117 // Flush the backup back to persistent storage in case we re-generated
118 // missing data above.
119 BackUpCurrentClientInfo();
123 // Failing attempts at getting an existing client ID, generate a new one.
124 client_id_
= base::GenerateGUID();
125 local_state_
->SetString(prefs::kMetricsClientID
, client_id_
);
127 if (local_state_
->GetString(prefs::kMetricsOldClientID
).empty()) {
128 // Record the timestamp of when the user opted in to UMA.
129 local_state_
->SetInt64(prefs::kMetricsReportingEnabledTimestamp
,
130 base::Time::Now().ToTimeT());
132 UMA_HISTOGRAM_BOOLEAN("UMA.ClientIdMigrated", true);
134 local_state_
->ClearPref(prefs::kMetricsOldClientID
);
136 BackUpCurrentClientInfo();
139 void MetricsStateManager::CheckForClonedInstall(
140 scoped_refptr
<base::SingleThreadTaskRunner
> task_runner
) {
141 DCHECK(!cloned_install_detector_
);
143 MachineIdProvider
* provider
= MachineIdProvider::CreateInstance();
147 cloned_install_detector_
.reset(new ClonedInstallDetector(provider
));
148 cloned_install_detector_
->CheckForClonedInstall(local_state_
, task_runner
);
151 scoped_ptr
<const base::FieldTrial::EntropyProvider
>
152 MetricsStateManager::CreateEntropyProvider() {
153 // For metrics reporting-enabled users, we combine the client ID and low
154 // entropy source to get the final entropy source. Otherwise, only use the low
156 // This has two useful properties:
157 // 1) It makes the entropy source less identifiable for parties that do not
158 // know the low entropy source.
159 // 2) It makes the final entropy source resettable.
160 const int low_entropy_source_value
= GetLowEntropySource();
161 UMA_HISTOGRAM_SPARSE_SLOWLY("UMA.LowEntropySourceValue",
162 low_entropy_source_value
);
163 if (IsMetricsReportingEnabled()) {
164 UpdateEntropySourceReturnedValue(ENTROPY_SOURCE_HIGH
);
165 const std::string high_entropy_source
=
166 client_id_
+ base::IntToString(low_entropy_source_value
);
167 return scoped_ptr
<const base::FieldTrial::EntropyProvider
>(
168 new SHA1EntropyProvider(high_entropy_source
));
171 UpdateEntropySourceReturnedValue(ENTROPY_SOURCE_LOW
);
172 #if defined(OS_ANDROID) || defined(OS_IOS)
173 return scoped_ptr
<const base::FieldTrial::EntropyProvider
>(
174 new CachingPermutedEntropyProvider(local_state_
,
175 low_entropy_source_value
,
176 kMaxLowEntropySize
));
178 return scoped_ptr
<const base::FieldTrial::EntropyProvider
>(
179 new PermutedEntropyProvider(low_entropy_source_value
,
180 kMaxLowEntropySize
));
185 scoped_ptr
<MetricsStateManager
> MetricsStateManager::Create(
186 PrefService
* local_state
,
187 const base::Callback
<bool(void)>& is_reporting_enabled_callback
,
188 const StoreClientInfoCallback
& store_client_info
,
189 const LoadClientInfoCallback
& retrieve_client_info
) {
190 scoped_ptr
<MetricsStateManager
> result
;
191 // Note: |instance_exists_| is updated in the constructor and destructor.
192 if (!instance_exists_
) {
193 result
.reset(new MetricsStateManager(local_state
,
194 is_reporting_enabled_callback
,
196 retrieve_client_info
));
198 return result
.Pass();
202 void MetricsStateManager::RegisterPrefs(PrefRegistrySimple
* registry
) {
203 registry
->RegisterBooleanPref(prefs::kMetricsResetIds
, false);
204 registry
->RegisterStringPref(prefs::kMetricsClientID
, std::string());
205 registry
->RegisterInt64Pref(prefs::kMetricsReportingEnabledTimestamp
, 0);
206 registry
->RegisterIntegerPref(prefs::kMetricsLowEntropySource
,
207 kLowEntropySourceNotSet
);
209 ClonedInstallDetector::RegisterPrefs(registry
);
210 CachingPermutedEntropyProvider::RegisterPrefs(registry
);
212 // TODO(asvitkine): Remove these once a couple of releases have passed.
213 // http://crbug.com/357704
214 registry
->RegisterStringPref(prefs::kMetricsOldClientID
, std::string());
215 registry
->RegisterIntegerPref(prefs::kMetricsOldLowEntropySource
, 0);
218 void MetricsStateManager::BackUpCurrentClientInfo() {
219 ClientInfo client_info
;
220 client_info
.client_id
= client_id_
;
221 client_info
.installation_date
= local_state_
->GetInt64(prefs::kInstallDate
);
222 client_info
.reporting_enabled_date
=
223 local_state_
->GetInt64(prefs::kMetricsReportingEnabledTimestamp
);
224 store_client_info_
.Run(client_info
);
227 scoped_ptr
<ClientInfo
> MetricsStateManager::LoadClientInfoAndMaybeMigrate() {
228 scoped_ptr
<ClientInfo
> client_info
= load_client_info_
.Run();
230 // Prior to 2014-07, the client ID was stripped of its dashes before being
231 // saved. Migrate back to a proper GUID if this is the case. This migration
232 // code can be removed in M41+.
233 const size_t kGUIDLengthWithoutDashes
= 32U;
235 client_info
->client_id
.length() == kGUIDLengthWithoutDashes
) {
236 DCHECK(client_info
->client_id
.find('-') == std::string::npos
);
238 std::string client_id_with_dashes
;
239 client_id_with_dashes
.reserve(kGUIDLengthWithoutDashes
+ 4U);
240 std::string::const_iterator client_id_it
= client_info
->client_id
.begin();
241 for (size_t i
= 0; i
< kGUIDLengthWithoutDashes
+ 4U; ++i
) {
242 if (i
== 8U || i
== 13U || i
== 18U || i
== 23U) {
243 client_id_with_dashes
.push_back('-');
245 client_id_with_dashes
.push_back(*client_id_it
);
249 DCHECK(client_id_it
== client_info
->client_id
.end());
250 client_info
->client_id
.assign(client_id_with_dashes
);
253 // The GUID retrieved (and possibly fixed above) should be valid unless
255 DCHECK(!client_info
|| base::IsValidGUID(client_info
->client_id
));
257 return client_info
.Pass();
260 int MetricsStateManager::GetLowEntropySource() {
261 // Note that the default value for the low entropy source and the default pref
262 // value are both kLowEntropySourceNotSet, which is used to identify if the
263 // value has been set or not.
264 if (low_entropy_source_
!= kLowEntropySourceNotSet
)
265 return low_entropy_source_
;
267 const base::CommandLine
* command_line(base::CommandLine::ForCurrentProcess());
268 // Only try to load the value from prefs if the user did not request a
270 // Otherwise, skip to generating a new value.
271 if (!command_line
->HasSwitch(switches::kResetVariationState
)) {
272 int value
= local_state_
->GetInteger(prefs::kMetricsLowEntropySource
);
273 // If the value is outside the [0, kMaxLowEntropySize) range, re-generate
275 if (value
>= 0 && value
< kMaxLowEntropySize
) {
276 low_entropy_source_
= value
;
277 UMA_HISTOGRAM_BOOLEAN("UMA.GeneratedLowEntropySource", false);
278 return low_entropy_source_
;
282 UMA_HISTOGRAM_BOOLEAN("UMA.GeneratedLowEntropySource", true);
283 low_entropy_source_
= GenerateLowEntropySource();
284 local_state_
->SetInteger(prefs::kMetricsLowEntropySource
,
285 low_entropy_source_
);
286 local_state_
->ClearPref(prefs::kMetricsOldLowEntropySource
);
287 CachingPermutedEntropyProvider::ClearCache(local_state_
);
289 return low_entropy_source_
;
292 void MetricsStateManager::UpdateEntropySourceReturnedValue(
293 EntropySourceType type
) {
294 if (entropy_source_returned_
!= ENTROPY_SOURCE_NONE
)
297 entropy_source_returned_
= type
;
298 UMA_HISTOGRAM_ENUMERATION("UMA.EntropySourceType", type
,
299 ENTROPY_SOURCE_ENUM_SIZE
);
302 void MetricsStateManager::ResetMetricsIDsIfNecessary() {
303 if (!local_state_
->GetBoolean(prefs::kMetricsResetIds
))
306 UMA_HISTOGRAM_BOOLEAN("UMA.MetricsIDsReset", true);
308 DCHECK(client_id_
.empty());
309 DCHECK_EQ(kLowEntropySourceNotSet
, low_entropy_source_
);
311 local_state_
->ClearPref(prefs::kMetricsClientID
);
312 local_state_
->ClearPref(prefs::kMetricsLowEntropySource
);
313 local_state_
->ClearPref(prefs::kMetricsResetIds
);
315 // Also clear the backed up client info.
316 store_client_info_
.Run(ClientInfo());
319 } // namespace metrics