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