Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(857)

Side by Side Diff: chrome/installer/setup/user_experiment.cc

Issue 2933043002: Installer support for Windows 10 inactive user toast. (Closed)
Patch Set: sync to position 479504 and patch set 17 of crrev.com/2889323004 Created 3 years, 6 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
(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/setup/user_experiment.h"
6
7 #include <windows.h>
8
9 #include <lm.h>
10 #include <shellapi.h>
11 #include <wtsapi32.h>
12
13 #include <memory>
14
15 #include "base/command_line.h"
16 #include "base/files/file_path.h"
17 #include "base/process/launch.h"
18 #include "base/process/process_info.h"
19 #include "base/rand_util.h"
20 #include "base/strings/string16.h"
21 #include "base/strings/string_number_conversions.h"
22 #include "base/win/registry.h"
23 #include "base/win/scoped_handle.h"
24 #include "base/win/scoped_process_information.h"
25 #include "base/win/win_util.h"
26 #include "base/win/windows_version.h"
27 #include "chrome/common/chrome_switches.h"
28 #include "chrome/common/chrome_version.h"
29 #include "chrome/install_static/install_modes.h"
30 #include "chrome/install_static/install_util.h"
31 #include "chrome/installer/setup/installer_state.h"
32 #include "chrome/installer/setup/setup_constants.h"
33 #include "chrome/installer/setup/setup_singleton.h"
34 #include "chrome/installer/setup/setup_util.h"
35 #include "chrome/installer/setup/update_active_setup_version_work_item.h"
36 #include "chrome/installer/util/experiment.h"
37 #include "chrome/installer/util/experiment_storage.h"
38 #include "chrome/installer/util/google_update_constants.h"
39 #include "chrome/installer/util/google_update_settings.h"
40 #include "chrome/installer/util/install_util.h"
41 #include "chrome/installer/util/util_constants.h"
42 #include "ui/base/fullscreen_win.h"
43
44 namespace installer {
45
46 namespace {
47
48 // The study currently being conducted.
49 constexpr ExperimentStorage::Study kCurrentStudy = ExperimentStorage::kStudyOne;
50
51 // The primary group for study number two.
52 constexpr int kStudyTwoGroup = 0;
53
54 // Test switches.
55 constexpr char kExperimentEnterpriseBypass[] = "experiment-enterprise-bypass";
56 constexpr char kExperimentParticipation[] = "experiment-participation";
57 constexpr char kExperimentRetryDelay[] = "experiment-retry-delay";
58
59 // Returns true if the install corresponds to an enterprise brand or if the
60 // machine is joined to a domain. This check can be bypassed via
61 // --experiment-enterprise-bypass.
62 bool IsEnterpriseInstall() {
63 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
64 kExperimentEnterpriseBypass)) {
65 return false;
66 }
67 return IsEnterpriseBrand() || IsDomainJoined();
68 }
69
70 // Returns the delay to be used between presentation retries. The default (five
71 // minutes) can be overidden via --experiment-retry-delay=SECONDS.
72 base::TimeDelta GetRetryDelay() {
73 base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
74 base::string16 value =
75 command_line->GetSwitchValueNative(kExperimentRetryDelay);
76 int seconds;
77 if (!value.empty() && base::StringToInt(value, &seconds))
78 return base::TimeDelta::FromSeconds(seconds);
79 return base::TimeDelta::FromMinutes(5);
80 }
81
82 // Overrides the participation value for testing if a value is provided via
83 // --experiment-participation=value. "value" may be "one" or "two". Any other
84 // value (or none at all) results in clearing the persisted state for organic
85 // re-evaluation.
86 ExperimentStorage::Study HandleParticipationOverride(
87 ExperimentStorage::Study current_participation,
88 ExperimentStorage::Lock* lock) {
89 base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
90 if (!command_line->HasSwitch(kExperimentParticipation))
91 return current_participation;
92
93 base::string16 participation_override =
94 command_line->GetSwitchValueNative(kExperimentParticipation);
95 ExperimentStorage::Study participation = ExperimentStorage::kNoStudySelected;
96 if (participation_override == L"one")
97 participation = ExperimentStorage::kStudyOne;
98 else if (participation_override == L"two")
99 participation = ExperimentStorage::kStudyTwo;
100
101 if (participation != current_participation)
102 lock->WriteParticipation(participation);
103
104 return participation;
105 }
106
107 // This function launches setup as the currently logged-in interactive
108 // user, that is, the user whose logon session is attached to winsta0\default.
109 // It assumes that currently we are running as SYSTEM in a non-interactive
110 // window station.
111 // The function fails if there is no interactive session active, basically
112 // the computer is on but nobody has logged in locally.
113 // Remote Desktop sessions do not count as interactive sessions; running this
114 // method as a user logged in via remote desktop will do nothing.
115 bool LaunchSetupAsConsoleUser(const base::CommandLine& cmd_line) {
116 DWORD console_id = ::WTSGetActiveConsoleSessionId();
117 if (console_id == 0xFFFFFFFF) {
118 PLOG(ERROR) << __func__ << " no session attached to the console";
119 return false;
120 }
121 base::win::ScopedHandle user_token_handle;
122 {
123 HANDLE user_token;
124 if (!::WTSQueryUserToken(console_id, &user_token)) {
125 PLOG(ERROR) << __func__ << " failed to get user token for console_id "
126 << console_id;
127 return false;
128 }
129 user_token_handle.Set(user_token);
130 }
131 base::LaunchOptions options;
132 options.as_user = user_token_handle.Get();
133 options.empty_desktop_name = true;
134 VLOG(1) << "Spawning experiment process: " << cmd_line.GetCommandLineString();
135 if (base::LaunchProcess(cmd_line, options).IsValid())
136 return true;
137 PLOG(ERROR) << "Failed";
138 return false;
139 }
140
141 // Returns true if the Windows shell indicates that the machine isn't in
142 // presentation mode, running a full-screen D3D app, or in a quiet period.
143 bool MayShowNotifications() {
144 QUERY_USER_NOTIFICATION_STATE state = {};
145 HRESULT result = SHQueryUserNotificationState(&state);
146 if (FAILED(result))
147 return true;
148 // Explicitly allow the acceptable states rather than the converse to be sure
149 // there are no surprises should new states be introduced.
150 return state == QUNS_NOT_PRESENT || // Locked/screensaver running.
151 state == QUNS_ACCEPTS_NOTIFICATIONS; // Go for it!
152 }
153
154 bool UserSessionIsNotYoung() {
155 static constexpr base::TimeDelta kMinSessionLength =
156 base::TimeDelta::FromMinutes(5);
157 base::Time session_start_time = GetConsoleSessionStartTime();
158 if (session_start_time.is_null())
159 return true;
160
161 base::TimeDelta session_length = base::Time::Now() - session_start_time;
162 return session_length >= kMinSessionLength;
163 }
164
165 bool ActiveWindowIsNotFullscreen() {
166 return !ui::IsFullScreenMode();
167 }
168
169 // Blocks processing if conditions are not right for presentation. Returns true
170 // if presentation should continue, or false otherwise (e.g., another process
171 // requires the setup singleton).
172 bool WaitForPresentation(
173 const SetupSingleton& setup_singleton,
174 Experiment* experiment,
175 ExperimentStorage* storage,
176 std::unique_ptr<ExperimentStorage::Lock>* storage_lock) {
177 base::TimeDelta retry_delay = GetRetryDelay();
178 bool first_sleep = true;
179 bool loop_again = true;
180
181 do {
182 if (MayShowNotifications() && UserSessionIsNotYoung() &&
183 ActiveWindowIsNotFullscreen()) {
184 return true;
185 }
186
187 // Update the state accordingly if this is the first sleep.
188 if (first_sleep) {
189 experiment->SetState(ExperimentMetrics::kDeferringPresentation);
190 (*storage_lock)->StoreExperiment(*experiment);
191 first_sleep = false;
192 }
193
194 // Release the storage lock and wait on the singleton for five minutes.
195 storage_lock->reset();
196 // Break when another process needs the singleton.
197 loop_again = !setup_singleton.WaitForInterrupt(retry_delay);
198 *storage_lock = storage->AcquireLock();
199 } while (loop_again);
200
201 return false;
202 }
203
204 } // namespace
205
206 // Execution may be in the context of the system or a user on it, and no
207 // guarantee is made regarding the setup singleton.
208 bool ShouldRunUserExperiment() {
209 if (!install_static::kUseGoogleUpdateIntegration)
210 return false;
211
212 if (!install_static::SupportsRetentionExperiments())
213 return false;
214
215 // The current experiment only applies to Windows 10 and newer.
216 if (base::win::GetVersion() < base::win::VERSION_WIN10)
217 return false;
218
219 // Enterprise brand codes and domain joined machines are excluded.
220 if (IsEnterpriseInstall())
221 return false;
222
223 // Gain exclusive access to the persistent experiment state. Only per-install
224 // state may be queried (participation and metrics are okay; Experiment itself
225 // is not).
226 ExperimentStorage storage;
227 auto lock = storage.AcquireLock();
228
229 // Bail out if this install is not selected into the fraction participating in
230 // the current study.
231 // NOTE: No clients will participate while this feature is under development.
232 if (true || !IsSelectedForStudy(lock.get(), kCurrentStudy))
233 return false;
234
235 // Skip the experiment if a user on the machine has already reached a terminal
236 // state.
237 ExperimentMetrics metrics;
238 if (!lock->LoadMetrics(&metrics) || metrics.InTerminalState())
239 return false;
240
241 return true;
242 }
243
244 // Execution is from the context of the installer immediately following a
245 // successful update. The setup singleton is held.
246 void BeginUserExperiment(const InstallerState& installer_state,
247 const base::FilePath& setup_path,
248 bool user_context) {
249 ExperimentStorage storage;
250
251 // Prepare a command line to relaunch the installed setup.exe for the
252 // experiment.
253 base::CommandLine setup_command(setup_path);
254 InstallUtil::AppendModeSwitch(&setup_command);
255 if (installer_state.system_install())
256 setup_command.AppendSwitch(switches::kSystemLevel);
257 if (installer_state.verbose_logging())
258 setup_command.AppendSwitch(switches::kVerboseLogging);
259 setup_command.AppendSwitch(switches::kUserExperiment);
260 // Copy any test switches used by the spawned process.
261 static constexpr const char* kSwitchesToCopy[] = {
262 kExperimentRetryDelay,
263 };
264 setup_command.CopySwitchesFrom(*base::CommandLine::ForCurrentProcess(),
265 kSwitchesToCopy, arraysize(kSwitchesToCopy));
266
267 if (user_context) {
268 // This is either a per-user install or a per-machine install run via
269 // Active Setup as a normal user.
270 DCHECK(!installer_state.system_install() ||
271 base::GetCurrentProcessIntegrityLevel() == base::MEDIUM_INTEGRITY);
272 VLOG(1) << "Spawning experiment process: "
273 << setup_command.GetCommandLineString();
274 // The installer is already running in the context of an ordinary user.
275 // Relaunch directly to run the experiment.
276 base::LaunchOptions launch_options;
277 launch_options.force_breakaway_from_job_ = true;
278 if (!base::LaunchProcess(setup_command, launch_options).IsValid()) {
279 LOG(ERROR) << __func__
280 << " failed to relaunch installer for user experiment,";
281 WriteInitialState(&storage, ExperimentMetrics::kRelaunchFailed);
282 }
283 return;
284 }
285
286 // The installer is running at high integrity, likely as SYSTEM. Relaunch as
287 // the console user at medium integrity.
288 VLOG(1) << "Attempting to spawn experiment as console user.";
289 if (LaunchSetupAsConsoleUser(setup_command)) {
290 return;
291 }
292
293 // Trigger Active Setup to run on the next user logon if this machine has
294 // never participated in the experiment. This will be done at most once per
295 // machine, even across updates. Doing so more often risks having excessive
296 // active setup activity for some users.
297 auto storage_lock = storage.AcquireLock();
298 ExperimentMetrics experiment_metrics;
299 if (storage_lock->LoadMetrics(&experiment_metrics) &&
300 experiment_metrics.state == ExperimentMetrics::kUninitialized) {
301 UpdateActiveSetupVersionWorkItem item(
302 install_static::GetActiveSetupPath(),
303 UpdateActiveSetupVersionWorkItem::UPDATE_AND_BUMP_SELECTIVE_TRIGGER);
304 if (item.Do()) {
305 VLOG(1) << "Bumped Active Setup Version for user experiment";
306 experiment_metrics.state = ExperimentMetrics::kWaitingForUserLogon;
307 storage_lock->StoreMetrics(experiment_metrics);
308 } else {
309 LOG(ERROR) << "Failed to bump Active Setup Version for user experiment.";
310 }
311 }
312 }
313
314 // This function executes within the context of a signed-in user, even for the
315 // case of system-level installs. In particular, it may be run in a spawned
316 // setup.exe immediately after a successful update or following user logon as a
317 // result of Active Setup.
318 void RunUserExperiment(const base::CommandLine& command_line,
319 const MasterPreferences& master_preferences,
320 InstallationState* original_state,
321 InstallerState* installer_state) {
322 VLOG(1) << __func__;
323
324 ExperimentStorage storage;
325 std::unique_ptr<SetupSingleton> setup_singleton(SetupSingleton::Acquire(
326 command_line, master_preferences, original_state, installer_state));
327 if (!setup_singleton) {
328 VLOG(1) << "Timed out while waiting for setup singleton";
329 WriteInitialState(&storage, ExperimentMetrics::kSingletonWaitTimeout);
330 return;
331 }
332
333 Experiment experiment;
334 auto storage_lock = storage.AcquireLock();
335
336 // Determine the study in which this client participates.
337 ExperimentStorage::Study participation = ExperimentStorage::kNoStudySelected;
338 if (!storage_lock->ReadParticipation(&participation) ||
339 participation == ExperimentStorage::kNoStudySelected) {
340 // ShouldRunUserExperiment should have brought this client into a particular
341 // study. Something is very wrong if it can't be determined here.
342 LOG(ERROR) << "Failed to read study participation.";
343 return;
344 }
345
346 if (!storage_lock->LoadExperiment(&experiment)) {
347 // The metrics correspond to a different user on the machine; nothing to do.
348 VLOG(1) << "Another user is participating in the experiment.";
349 return;
350 }
351
352 // There is nothing to do if the user has already reached a terminal state.
353 if (experiment.metrics().InTerminalState()) {
354 VLOG(1) << "Experiment has reached terminal state: "
355 << experiment.metrics().state;
356 return;
357 }
358
359 // Now the fun begins. Assign this user to a group if this is the first time
360 // through.
361 if (experiment.metrics().InInitialState()) {
362 experiment.AssignGroup(PickGroup(participation));
363 VLOG(1) << "Assigned user to experiment group: "
364 << experiment.metrics().group;
365 }
366
367 // Chrome is considered actively used if it has been run within the last 28
368 // days or if it was installed within the same time period.
369 int days_ago_last_run = GoogleUpdateSettings::GetLastRunTime();
370 if ((days_ago_last_run >= 0 ? days_ago_last_run
371 : GetInstallAge(*installer_state)) <= 28) {
372 VLOG(1) << "Aborting experiment due to activity.";
373 experiment.SetState(ExperimentMetrics::kIsActive);
374 storage_lock->StoreExperiment(experiment);
375 return;
376 }
377
378 // Check for a dormant user: one for which the machine has been off or the
379 // user has been signed out for more than 90% of the last 28 days.
380 if (false) { // TODO(grt): Implement this.
381 VLOG(1) << "Aborting experiment due to dormancy.";
382 experiment.SetState(ExperimentMetrics::kIsDormant);
383 storage_lock->StoreExperiment(experiment);
384 return;
385 }
386
387 if (base::win::IsTabletDevice(nullptr)) {
388 VLOG(1) << "Aborting experiment due to tablet device.";
389 experiment.SetState(ExperimentMetrics::kIsTabletDevice);
390 storage_lock->StoreExperiment(experiment);
391 return;
392 }
393
394 if (IsUpdateRenamePending()) {
395 VLOG(1) << "Aborting experiment due to Chrome update rename pending.";
396 experiment.SetState(ExperimentMetrics::kIsUpdateRenamePending);
397 storage_lock->StoreExperiment(experiment);
398 return;
399 }
400
401 if (!WaitForPresentation(*setup_singleton, &experiment, &storage,
402 &storage_lock)) {
403 VLOG(1) << "Aborting experiment while waiting to present.";
404 experiment.SetState(ExperimentMetrics::kDeferredPresentationAborted);
405 storage_lock->StoreExperiment(experiment);
406 return;
407 }
408
409 VLOG(1) << "Launching Chrome to show the toast.";
410 experiment.SetState(ExperimentMetrics::kLaunchingChrome);
411 storage_lock->StoreExperiment(experiment);
412 LaunchChrome(*installer_state, experiment);
413 }
414
415 // Writes the initial state |state| to the registry if there is no existing
416 // state for this or another user.
417 void WriteInitialState(ExperimentStorage* storage,
418 ExperimentMetrics::State state) {
419 auto storage_lock = storage->AcquireLock();
420
421 // Write the state provided that there is either no existing state or that
422 // any that exists also represents an initial state.
423 ExperimentMetrics experiment_metrics;
424 if (storage_lock->LoadMetrics(&experiment_metrics) &&
425 experiment_metrics.InInitialState()) {
426 experiment_metrics.state = state;
427 storage_lock->StoreMetrics(experiment_metrics);
428 }
429 }
430
431 bool IsEnterpriseBrand() {
432 base::string16 brand;
433
434 if (!GoogleUpdateSettings::GetBrand(&brand))
435 return false;
436
437 if (brand.length() != 4)
438 return false;
439
440 if (brand == L"GGRV")
441 return true;
442
443 return brand[0] == L'G' && brand[1] == L'C' && brand[2] == L'E' &&
444 brand[3] != L'L' && brand[3] >= L'A' && brand[3] <= L'U';
445 }
446
447 bool IsDomainJoined() {
448 LPWSTR buffer = nullptr;
449 NETSETUP_JOIN_STATUS buffer_type = NetSetupUnknownStatus;
450 bool is_joined =
451 ::NetGetJoinInformation(nullptr, &buffer, &buffer_type) == NERR_Success &&
452 buffer_type == NetSetupDomainName;
453 if (buffer)
454 NetApiBufferFree(buffer);
455
456 return is_joined;
457 }
458
459 bool IsSelectedForStudy(ExperimentStorage::Lock* lock,
460 ExperimentStorage::Study current_study) {
461 ExperimentStorage::Study participation = ExperimentStorage::kNoStudySelected;
462 if (!lock->ReadParticipation(&participation))
463 return false;
464
465 participation = HandleParticipationOverride(participation, lock);
466
467 if (participation == ExperimentStorage::kNoStudySelected) {
468 // This install has not been evaluated for participation. Do so now. Select
469 // a small population into the first study of the experiment. Everyone else
470 // gets the second study.
471 participation = base::RandDouble() <= 0.02756962532
472 ? ExperimentStorage::kStudyOne
473 : ExperimentStorage::kStudyTwo;
474 if (!lock->WriteParticipation(participation))
475 return false;
476 }
477
478 return participation <= current_study;
479 }
480
481 int PickGroup(ExperimentStorage::Study participation) {
482 DCHECK(participation == ExperimentStorage::kStudyOne ||
483 participation == ExperimentStorage::kStudyTwo);
484 static constexpr int kHoldbackGroup = ExperimentMetrics::kNumGroups - 1;
485
486 if (participation == ExperimentStorage::kStudyOne) {
487 // Evenly distrubute clients among the groups.
488 return base::RandInt(0, ExperimentMetrics::kNumGroups - 1);
489 }
490
491 // 1% holdback, 99% in the winning group.
492 return base::RandDouble() < 0.01 ? kHoldbackGroup : kStudyTwoGroup;
493 }
494
495 bool IsUpdateRenamePending() {
496 // Consider an update to be pending if an "opv" value is present in the
497 // registry or if Chrome's version as registered with Omaha doesn't match the
498 // current version.
499 base::string16 clients_key_path =
500 install_static::GetClientsKeyPath(install_static::GetAppGuid());
501 const HKEY root = install_static::IsSystemInstall() ? HKEY_LOCAL_MACHINE
502 : HKEY_CURRENT_USER;
503 base::win::RegKey clients_key;
504
505 // The failure modes below are generally indicitive of a run from a
506 // non-installed Chrome. Pretend that all is well.
507 if (clients_key.Open(root, clients_key_path.c_str(),
508 KEY_WOW64_64KEY | KEY_QUERY_VALUE) != ERROR_SUCCESS) {
509 return false;
510 }
511 if (clients_key.HasValue(google_update::kRegOldVersionField))
512 return true;
513 base::string16 product_version;
514 if (clients_key.ReadValue(google_update::kRegVersionField,
515 &product_version) != ERROR_SUCCESS) {
516 return false;
517 }
518 return product_version != TEXT(CHROME_VERSION_STRING);
519 }
520
521 void LaunchChrome(const InstallerState& installer_state,
522 const Experiment& experiment) {
523 const base::FilePath chrome_exe =
524 installer_state.target_path().Append(kChromeExe);
525 base::CommandLine command_line(chrome_exe);
526 command_line.AppendSwitchNative(::switches::kTryChromeAgain,
527 base::IntToString16(experiment.group()));
528
529 STARTUPINFOW startup_info = {sizeof(startup_info)};
530 PROCESS_INFORMATION temp_process_info = {};
531 base::string16 writable_command_line_string(
532 command_line.GetCommandLineString());
533 if (!::CreateProcess(
534 chrome_exe.value().c_str(), &writable_command_line_string[0],
535 nullptr /* lpProcessAttributes */, nullptr /* lpThreadAttributes */,
536 FALSE /* bInheritHandles */, CREATE_NO_WINDOW,
537 nullptr /* lpEnvironment */, nullptr /* lpCurrentDirectory */,
538 &startup_info, &temp_process_info)) {
539 PLOG(ERROR) << "Failed to launch: " << writable_command_line_string;
540 return;
541 }
542
543 base::win::ScopedProcessInformation process_info(temp_process_info);
Patrick Monette 2017/06/14 22:28:08 This is used only to close handles?
grt (UTC plus 2) 2017/06/15 09:27:37 Yup; comment added.
544 }
545
546 } // namespace installer
OLDNEW
« no previous file with comments | « chrome/installer/setup/user_experiment.h ('k') | chrome/installer/setup/user_experiment_unittest.cc » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698