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

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

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