OLD | NEW |
---|---|
(Empty) | |
1 // Copyright 2017 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/installer/util/experiment_storage.h" | |
6 | |
7 #include <windows.h> | |
8 | |
9 #include <stdint.h> | |
10 | |
11 #include <limits> | |
12 #include <string> | |
13 | |
14 #include "base/base64.h" | |
15 #include "base/bind.h" | |
16 #include "base/bind_helpers.h" | |
17 #include "base/logging.h" | |
18 #include "base/memory/ptr_util.h" | |
19 #include "base/strings/utf_string_conversions.h" | |
20 #include "base/task_scheduler/post_task.h" | |
21 #include "base/task_scheduler/task_traits.h" | |
22 #include "base/time/time.h" | |
23 #include "base/win/registry.h" | |
24 #include "base/win/win_util.h" | |
25 #include "chrome/install_static/install_details.h" | |
26 #include "chrome/install_static/install_modes.h" | |
27 #include "chrome/install_static/install_util.h" | |
28 #include "chrome/installer/util/experiment.h" | |
29 #include "chrome/installer/util/experiment_labels.h" | |
30 #include "chrome/installer/util/experiment_metrics.h" | |
31 #include "chrome/installer/util/google_update_settings.h" | |
32 #include "chrome/installer/util/shell_util.h" | |
33 | |
34 namespace installer { | |
35 | |
36 namespace { | |
37 | |
38 constexpr base::char16 kExperimentLabelName[] = L"CrExp60"; | |
39 constexpr wchar_t kRegKeyRetention[] = L"Retention"; | |
40 constexpr wchar_t kRegValueActionDelay[] = L"ActionDelay"; | |
41 constexpr wchar_t kRegValueFirstDisplayTime[] = L"FirstDisplayTime"; | |
42 constexpr wchar_t kRegValueGroup[] = L"Group"; | |
43 constexpr wchar_t kRegValueInactiveDays[] = L"InactiveDays"; | |
44 constexpr wchar_t kRegValueLatestDisplayTime[] = L"LatestDisplayTime"; | |
45 constexpr wchar_t kRegValueRetentionStudy[] = L"RetentionStudy"; | |
46 constexpr wchar_t kRegValueState[] = L"State"; | |
47 constexpr wchar_t kRegValueToastCount[] = L"ToastCount"; | |
48 constexpr wchar_t kRegValueToastLocation[] = L"ToastLocation"; | |
49 constexpr wchar_t kRegValueUserSessionUptime[] = L"UserSessionUptime"; | |
50 | |
51 static constexpr int kSessionLengthLowestBit = 0; | |
grt (UTC plus 2)
2017/05/24 13:43:38
nit: omit "static" in an unnamed namespace
nikunjb
2017/05/30 21:45:01
Done.
| |
52 static constexpr int kDisplayTimeBucketLowestBit = | |
53 ExperimentMetrics::kSessionLengthBits + kSessionLengthLowestBit; | |
54 static constexpr int kLastUsedBucketLowestBit = | |
55 ExperimentMetrics::kDisplayTimeBucketBits + kDisplayTimeBucketLowestBit; | |
56 static constexpr int kToastHourLowestBit = | |
57 ExperimentMetrics::kLastUsedBucketBits + kLastUsedBucketLowestBit; | |
58 static constexpr int kFirstToastOffsetLowestBit = | |
59 ExperimentMetrics::kToastHourBits + kToastHourLowestBit; | |
60 static constexpr int kToastCountLowestBit = | |
61 ExperimentMetrics::kFirstToastOffsetBits + kFirstToastOffsetLowestBit; | |
62 static constexpr int kToastLocationLowestBit = | |
63 ExperimentMetrics::kToastCountBits + kToastCountLowestBit; | |
64 static constexpr int kStateLowestBit = | |
65 ExperimentMetrics::kToastLocationBits + kToastLocationLowestBit; | |
66 static constexpr int kGroupLowestBit = | |
67 ExperimentMetrics::kStateBits + kStateLowestBit; | |
68 | |
69 // Helper functions ------------------------------------------------------------ | |
70 | |
71 // Returns the name of the global mutex used to protect the storage location. | |
72 base::string16 GetMutexName() { | |
73 base::string16 name(L"Global\\"); | |
74 name.append(install_static::kCompanyPathName); | |
75 name.append(ShellUtil::GetBrowserModelId(!install_static::IsSystemInstall())); | |
76 name.append(L"ExperimentStorageMutex"); | |
77 return name; | |
78 } | |
79 | |
80 // Populates |path| with the path to the registry key in which the current | |
81 // user's experiment state is stored. Returns false if the path cannot be | |
82 // determined. | |
83 bool GetExperimentStateKeyPath(bool system_level, base::string16* path) { | |
84 const install_static::InstallDetails& install_details = | |
85 install_static::InstallDetails::Get(); | |
86 | |
87 if (!system_level) { | |
88 *path = install_details.GetClientStateKeyPath().append(kRegKeyRetention); | |
89 return true; | |
90 } | |
91 | |
92 base::string16 user_sid; | |
93 if (base::win::GetUserSidString(&user_sid)) { | |
94 *path = install_details.GetClientStateMediumKeyPath() | |
95 .append(L"\\") | |
96 .append(kRegKeyRetention) | |
97 .append(L"\\") | |
98 .append(user_sid); | |
99 return true; | |
100 } | |
101 | |
102 NOTREACHED(); | |
103 return false; | |
104 } | |
105 | |
106 bool OpenParticipationKey(bool write_access, base::win::RegKey* key) { | |
107 const install_static::InstallDetails& details = | |
108 install_static::InstallDetails::Get(); | |
109 LONG result = key->Open( | |
110 details.system_level() ? HKEY_LOCAL_MACHINE : HKEY_CURRENT_USER, | |
111 details.GetClientStateKeyPath().c_str(), | |
112 KEY_WOW64_32KEY | (write_access ? KEY_SET_VALUE : KEY_QUERY_VALUE)); | |
113 return result == ERROR_SUCCESS; | |
114 } | |
115 | |
116 // Reads |value_name| into |result|. Returns false if the value is not found or | |
117 // is out of range. | |
118 template <class T> | |
119 bool ReadBoundedDWORD(base::win::RegKey* key, | |
120 const wchar_t* value_name, | |
121 DWORD min_value, | |
122 DWORD max_value, | |
123 T* result) { | |
124 DWORD dword_value; | |
125 if (key->ReadValueDW(value_name, &dword_value) != ERROR_SUCCESS) | |
126 return false; | |
127 if (dword_value < min_value || dword_value > max_value) | |
128 return false; | |
129 *result = static_cast<T>(dword_value); | |
130 return true; | |
131 } | |
132 | |
133 // Reads the internal representation of a Time or TimeDelta from |value_name| | |
134 // into |result|. Returns false if the value is not found or is out of range. | |
135 template <class T> | |
136 bool ReadTime(base::win::RegKey* key, const wchar_t* value_name, T* result) { | |
137 int64_t qword_value; | |
138 if (key->ReadInt64(value_name, &qword_value) != ERROR_SUCCESS) | |
139 return false; | |
140 if (qword_value > std::numeric_limits<int64_t>::max()) | |
141 return false; | |
142 *result = T::FromInternalValue(static_cast<int64_t>(qword_value)); | |
143 return true; | |
144 } | |
145 | |
146 void WriteTime(base::win::RegKey* key, | |
147 const wchar_t* value_name, | |
148 int64_t internal_time_value) { | |
149 key->WriteValue(value_name, &internal_time_value, sizeof(internal_time_value), | |
150 REG_QWORD); | |
151 } | |
152 | |
153 } // namespace | |
154 | |
155 // ExperimentStorage::Lock ----------------------------------------------------- | |
156 | |
157 ExperimentStorage::Lock::~Lock() { | |
158 BOOL result = ::ReleaseMutex(storage_->mutex_.Get()); | |
159 DCHECK(result); | |
160 } | |
161 | |
162 bool ExperimentStorage::Lock::ReadParticipation(Participation* participation) { | |
163 base::win::RegKey key; | |
164 // A failure to open the key likely indicates that this isn't running from a | |
165 // real install of Chrome. | |
166 if (!OpenParticipationKey(false /* !write_access */, &key)) | |
167 return false; | |
168 | |
169 DWORD value = 0; | |
170 LONG result = key.ReadValueDW(kRegValueRetentionStudy, &value); | |
171 if (result != ERROR_SUCCESS) { | |
172 // This likely means that the value is not present. | |
173 *participation = Participation::kNotEvaluated; | |
174 } else if (value == 0) { | |
175 *participation = Participation::kNotParticipating; | |
176 } else { | |
177 *participation = Participation::kIsParticipating; | |
178 } | |
179 return true; | |
180 } | |
181 | |
182 bool ExperimentStorage::Lock::WriteParticipation(Participation participation) { | |
183 base::win::RegKey key; | |
184 // A failure to open the key likely indicates that this isn't running from a | |
185 // real install of Chrome. | |
186 if (!OpenParticipationKey(true /* write_access */, &key)) | |
187 return false; | |
188 | |
189 if (participation == Participation::kNotEvaluated) | |
190 return key.DeleteValue(kRegValueRetentionStudy) == ERROR_SUCCESS; | |
191 const DWORD value = participation == Participation::kIsParticipating ? 1 : 0; | |
192 return key.WriteValue(kRegValueRetentionStudy, value) == ERROR_SUCCESS; | |
193 } | |
194 | |
195 bool ExperimentStorage::Lock::LoadExperiment(Experiment* experiment) { | |
196 // This function loads both the experiment metrics and state from the | |
197 // registry. | |
198 // - If no metrics are found: |experiment| is cleared, and true is returned. | |
199 // (Per-user experiment data in the registry is ignored for all users.) | |
200 // - If metrics indicate an initial state (prior to a user being elected into | |
201 // an experiment group): |experiment| is populated with the metrics and true | |
202 // is returned. (Per-user experiment data in the registry is ignored for all | |
203 // users.) | |
204 // - If metrics indicate an intermediate or terminal state and per-user | |
205 // experiment data is in the same state: |experiment| is populated with all | |
206 // data from the registry and true is returned. | |
207 // Otherwise, the metrics correspond to a different user on the machine, so | |
208 // false is returned. | |
209 | |
210 *experiment = Experiment(); | |
211 | |
212 ExperimentMetrics metrics; | |
213 if (!storage_->LoadMetricsUnsafe(&metrics)) | |
214 return false; // Error reading metrics -- do nothing. | |
215 | |
216 if (metrics.InInitialState()) { | |
217 // There should be no per-user experiment data present (ignore it if there | |
218 // happens to be somehow). | |
219 experiment->InitializeFromMetrics(metrics); | |
220 return true; | |
221 } | |
222 | |
223 Experiment temp_experiment; | |
224 if (!storage_->LoadStateUnsafe(&temp_experiment)) | |
225 return false; | |
226 | |
227 // Verify that the state matches the metrics. Ignore the state if this is not | |
228 // the case, as the metrics are the source of truth. | |
229 if (temp_experiment.state_ != metrics.state) | |
230 return false; | |
231 | |
232 *experiment = temp_experiment; | |
233 return true; | |
234 } | |
235 | |
236 bool ExperimentStorage::Lock::StoreExperiment(const Experiment& experiment) { | |
237 bool ret = storage_->StoreMetricsUnsafe(experiment.metrics()); | |
238 return storage_->StoreStateUnsafe(experiment) && ret; | |
239 } | |
240 | |
241 bool ExperimentStorage::Lock::LoadMetrics(ExperimentMetrics* metrics) { | |
242 return storage_->LoadMetricsUnsafe(metrics); | |
243 } | |
244 | |
245 bool ExperimentStorage::Lock::StoreMetrics(const ExperimentMetrics& metrics) { | |
246 return storage_->StoreMetricsUnsafe(metrics); | |
247 } | |
248 | |
249 ExperimentStorage::Lock::Lock(ExperimentStorage* storage) : storage_(storage) { | |
250 DCHECK(storage); | |
251 DWORD result = ::WaitForSingleObject(storage_->mutex_.Get(), INFINITE); | |
252 PLOG_IF(FATAL, result == WAIT_FAILED) | |
253 << "Failed to lock ExperimentStorage mutex"; | |
254 } | |
255 | |
256 // ExperimentStorage ----------------------------------------------------------- | |
257 | |
258 ExperimentStorage::ExperimentStorage() | |
259 : mutex_(::CreateMutex(nullptr, FALSE, GetMutexName().c_str())) {} | |
260 | |
261 ExperimentStorage::~ExperimentStorage() {} | |
262 | |
263 std::unique_ptr<ExperimentStorage::Lock> ExperimentStorage::AcquireLock() { | |
264 return base::WrapUnique(new Lock(this)); | |
265 } | |
266 | |
267 // static | |
268 int ExperimentStorage::ReadUint64Bits(uint64_t source, int len, int low_bit) { | |
269 DCHECK(len > 0 && len <= 32 && low_bit + len <= 64); | |
270 uint64_t bit_mask = (uint64_t(1) << len) - 1; | |
271 return static_cast<int>((source >> low_bit) & bit_mask); | |
272 } | |
273 | |
274 // static | |
275 void ExperimentStorage::SetUint64Bits(int value, | |
276 int len, | |
277 int low_bit, | |
278 uint64_t* source) { | |
279 DCHECK(len > 0 && len <= 32); | |
280 << "Can not read an int of length " << len << " from " << value; | |
grt (UTC plus 2)
2017/05/24 13:43:38
oops :-)
nikunjb
2017/05/30 21:45:01
Done.
| |
281 uint64_t bit_mask = (uint64_t(1) << len) - 1; | |
282 *source |= ((uint64_t(value) & bit_mask) << low_bit); | |
283 } | |
284 | |
285 bool ExperimentStorage::DecodeMetrics(base::StringPiece16 encoded_metrics, | |
286 ExperimentMetrics* metrics) { | |
287 std::string metrics_data; | |
288 | |
289 if (!base::Base64Decode(base::UTF16ToASCII(encoded_metrics), &metrics_data)) | |
290 return false; | |
291 | |
292 if (metrics_data.size() != 6) | |
293 return false; | |
294 | |
295 uint64_t metrics_value = 0; | |
296 for (int i = 0; i < metrics_data.size(); ++i) { | |
297 SetUint64Bits(metrics_data[i], 8, 8 * i, &metrics_value); | |
298 } | |
299 | |
300 ExperimentMetrics result; | |
301 result.session_length_bucket = | |
302 ReadUint64Bits(metrics_value, ExperimentMetrics::kSessionLengthBits, | |
303 kSessionLengthLowestBit); | |
304 result.display_time_bucket = | |
305 ReadUint64Bits(metrics_value, ExperimentMetrics::kDisplayTimeBucketBits, | |
306 kDisplayTimeBucketLowestBit); | |
307 result.last_used_bucket = | |
308 ReadUint64Bits(metrics_value, ExperimentMetrics::kLastUsedBucketBits, | |
309 kLastUsedBucketLowestBit); | |
310 result.toast_hour = ReadUint64Bits( | |
311 metrics_value, ExperimentMetrics::kToastHourBits, kToastHourLowestBit); | |
312 result.first_toast_offset = | |
313 ReadUint64Bits(metrics_value, ExperimentMetrics::kFirstToastOffsetBits, | |
314 kFirstToastOffsetLowestBit); | |
315 result.toast_count = ReadUint64Bits( | |
316 metrics_value, ExperimentMetrics::kToastCountBits, kToastCountLowestBit); | |
317 result.toast_location = static_cast<ExperimentMetrics::ToastLocation>( | |
318 ReadUint64Bits(metrics_value, ExperimentMetrics::kToastLocationBits, | |
319 kToastLocationLowestBit)); | |
320 | |
321 static_assert(ExperimentMetrics::State::NUM_STATES <= (1 << 4), | |
322 "Too many states for ExperimentMetrics encoding."); | |
323 result.state = static_cast<ExperimentMetrics::State>(ReadUint64Bits( | |
324 metrics_value, ExperimentMetrics::kStateBits, kStateLowestBit)); | |
325 result.group = ReadUint64Bits(metrics_value, ExperimentMetrics::kGroupBits, | |
326 kGroupLowestBit); | |
327 | |
328 int lowest_unused_bit = ExperimentMetrics::kGroupBits + kGroupLowestBit; | |
329 if (ReadUint64Bits(metrics_value, 64 - lowest_unused_bit, | |
330 lowest_unused_bit) != 0) | |
331 return false; | |
332 | |
333 *metrics = result; | |
334 return true; | |
335 } | |
336 | |
337 // static | |
338 base::string16 ExperimentStorage::EncodeMetrics( | |
339 const ExperimentMetrics& metrics) { | |
340 uint64_t metrics_value = 0; | |
341 SetUint64Bits(metrics.session_length_bucket, | |
342 ExperimentMetrics::kSessionLengthBits, kSessionLengthLowestBit, | |
343 &metrics_value); | |
344 SetUint64Bits(metrics.display_time_bucket, | |
345 ExperimentMetrics::kDisplayTimeBucketBits, | |
346 kDisplayTimeBucketLowestBit, &metrics_value); | |
347 SetUint64Bits(metrics.last_used_bucket, | |
348 ExperimentMetrics::kLastUsedBucketBits, | |
349 kLastUsedBucketLowestBit, &metrics_value); | |
350 SetUint64Bits(metrics.toast_hour, ExperimentMetrics::kToastHourBits, | |
351 kToastHourLowestBit, &metrics_value); | |
352 SetUint64Bits(metrics.first_toast_offset, | |
353 ExperimentMetrics::kFirstToastOffsetBits, | |
354 kFirstToastOffsetLowestBit, &metrics_value); | |
355 SetUint64Bits(metrics.toast_count, ExperimentMetrics::kToastCountBits, | |
356 kToastCountLowestBit, &metrics_value); | |
357 SetUint64Bits(metrics.toast_location, ExperimentMetrics::kToastLocationBits, | |
358 kToastLocationLowestBit, &metrics_value); | |
359 static_assert(ExperimentMetrics::State::NUM_STATES <= (1 << 4), | |
360 "Too many states for ExperimentMetrics encoding."); | |
361 SetUint64Bits(metrics.state, ExperimentMetrics::kStateBits, kStateLowestBit, | |
362 &metrics_value); | |
363 SetUint64Bits(metrics.group, ExperimentMetrics::kGroupBits, kGroupLowestBit, | |
364 &metrics_value); | |
365 | |
366 std::string metrics_data(6, '\0'); | |
367 for (int i = 0; i < metrics_data.size(); ++i) { | |
368 metrics_data[i] = | |
369 static_cast<char>(ReadUint64Bits(metrics_value, 8, 8 * i)); | |
370 } | |
371 std::string encoded_metrics; | |
372 base::Base64Encode(metrics_data, &encoded_metrics); | |
373 return base::ASCIIToUTF16(encoded_metrics); | |
374 } | |
375 | |
376 bool ExperimentStorage::LoadMetricsUnsafe(ExperimentMetrics* metrics) { | |
377 base::string16 value; | |
378 | |
379 if (!GoogleUpdateSettings::ReadExperimentLabels( | |
380 install_static::IsSystemInstall(), &value)) { | |
381 return false; | |
382 } | |
383 | |
384 ExperimentLabels experiment_labels(value); | |
385 base::StringPiece16 encoded_metrics = | |
386 experiment_labels.GetValueForLabel(kExperimentLabelName); | |
387 if (encoded_metrics.empty()) { | |
388 *metrics = ExperimentMetrics(); | |
389 return true; | |
390 } | |
391 | |
392 return DecodeMetrics(encoded_metrics, metrics); | |
393 } | |
394 | |
395 bool ExperimentStorage::StoreMetricsUnsafe(const ExperimentMetrics& metrics) { | |
396 base::string16 value; | |
397 if (!GoogleUpdateSettings::ReadExperimentLabels( | |
398 install_static::IsSystemInstall(), &value)) { | |
399 return false; | |
400 } | |
401 ExperimentLabels experiment_labels(value); | |
402 | |
403 experiment_labels.SetValueForLabel(kExperimentLabelName, | |
404 EncodeMetrics(metrics), | |
405 base::TimeDelta::FromDays(182)); | |
406 | |
407 return GoogleUpdateSettings::SetExperimentLabels( | |
408 install_static::IsSystemInstall(), experiment_labels.value()); | |
409 // TODO(grt): Update the "client" value here if needed and if possible. | |
410 // Updates must take place at high integrity, or via a registry handle | |
411 // provided by a high integrity caller. | |
412 } | |
413 | |
414 bool ExperimentStorage::LoadStateUnsafe(Experiment* experiment) { | |
415 const bool system_level = install_static::IsSystemInstall(); | |
416 | |
417 base::string16 path; | |
418 if (!GetExperimentStateKeyPath(system_level, &path)) | |
419 return false; | |
420 | |
421 const HKEY root = system_level ? HKEY_LOCAL_MACHINE : HKEY_CURRENT_USER; | |
422 base::win::RegKey key; | |
423 if (key.Open(root, path.c_str(), KEY_QUERY_VALUE | KEY_WOW64_32KEY) != | |
424 ERROR_SUCCESS) { | |
425 return false; | |
426 } | |
427 | |
428 return ReadBoundedDWORD(&key, kRegValueState, 0, | |
429 ExperimentMetrics::NUM_STATES, &experiment->state_) && | |
430 ReadBoundedDWORD(&key, kRegValueGroup, 0, | |
431 ExperimentMetrics::kNumGroups - 1, | |
432 &experiment->group_) && | |
433 ReadBoundedDWORD(&key, kRegValueToastLocation, 0, 1, | |
434 &experiment->toast_location_) && | |
435 ReadBoundedDWORD(&key, kRegValueInactiveDays, 0, INT_MAX, | |
436 &experiment->inactive_days_) && | |
437 ReadBoundedDWORD(&key, kRegValueToastCount, 0, | |
438 ExperimentMetrics::kMaxToastCount, | |
439 &experiment->toast_count_) && | |
440 ReadTime(&key, kRegValueFirstDisplayTime, | |
441 &experiment->first_display_time_) && | |
442 ReadTime(&key, kRegValueLatestDisplayTime, | |
443 &experiment->latest_display_time_) && | |
444 ReadTime(&key, kRegValueUserSessionUptime, | |
445 &experiment->user_session_uptime_) && | |
446 ReadTime(&key, kRegValueActionDelay, &experiment->action_delay_); | |
447 } | |
448 | |
449 bool ExperimentStorage::StoreStateUnsafe(const Experiment& experiment) { | |
450 const bool system_level = install_static::IsSystemInstall(); | |
451 | |
452 base::string16 path; | |
453 if (!GetExperimentStateKeyPath(system_level, &path)) | |
454 return false; | |
455 | |
456 const HKEY root = system_level ? HKEY_LOCAL_MACHINE : HKEY_CURRENT_USER; | |
457 base::win::RegKey key; | |
458 if (key.Create(root, path.c_str(), KEY_SET_VALUE | KEY_WOW64_32KEY) != | |
459 ERROR_SUCCESS) { | |
460 return false; | |
461 } | |
462 | |
463 key.WriteValue(kRegValueState, experiment.state_); | |
464 key.WriteValue(kRegValueGroup, experiment.group_); | |
465 key.WriteValue(kRegValueToastLocation, experiment.toast_location_); | |
466 key.WriteValue(kRegValueInactiveDays, experiment.inactive_days_); | |
467 key.WriteValue(kRegValueToastCount, experiment.toast_count_); | |
468 WriteTime(&key, kRegValueFirstDisplayTime, | |
469 experiment.first_display_time_.ToInternalValue()); | |
470 WriteTime(&key, kRegValueLatestDisplayTime, | |
471 experiment.latest_display_time_.ToInternalValue()); | |
472 WriteTime(&key, kRegValueUserSessionUptime, | |
473 experiment.user_session_uptime_.ToInternalValue()); | |
474 WriteTime(&key, kRegValueActionDelay, | |
475 experiment.action_delay_.ToInternalValue()); | |
476 return true; | |
477 } | |
478 | |
479 scoped_refptr<base::SingleThreadTaskRunner> ExperimentStorage::GetTaskRunner() { | |
480 if (!task_runner_) { | |
481 task_runner_ = base::CreateCOMSTATaskRunnerWithTraits(base::TaskTraits( | |
482 base::TaskPriority::BACKGROUND, | |
483 base::TaskShutdownBehavior::CONTINUE_ON_SHUTDOWN, base::MayBlock())); | |
484 } | |
485 return task_runner_; | |
486 } | |
487 | |
488 } // namespace installer | |
OLD | NEW |