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

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

Issue 2933043002: Installer support for Windows 10 inactive user toast. (Closed)
Patch Set: now with some tests 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 // windowstation.
Patrick Monette 2017/06/13 19:13:42 space?
grt (UTC plus 2) 2017/06/14 20:43:44 Done.
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.
Patrick Monette 2017/06/13 19:13:41 Whats the rationale for showing the notification w
grt (UTC plus 2) 2017/06/14 20:43:44 So that the toast is there on the desktop when you
151 state == QUNS_ACCEPTS_NOTIFICATIONS; // Go for it!
152 }
153
154 bool UserSessionIsNotYoung() {
155 base::Time session_start_time = GetConsoleSessionStartTime();
156 if (session_start_time.is_null())
157 return true;
158
159 base::TimeDelta session_length = base::Time::Now() - session_start_time;
160 return session_length >= base::TimeDelta::FromMinutes(5);
Patrick Monette 2017/06/13 19:13:41 Give a name to this 5 minutes constant
grt (UTC plus 2) 2017/06/14 20:43:44 Done.
161 }
162
163 bool ActiveWindowIsNotFullscreen() {
164 return !ui::IsFullScreenMode();
165 }
166
167 // Blocks processing if conditions are not right for presentation. Returns true
168 // if presentation should continue, or false otherwise (e.g., another process
169 // requires the setup singleton).
170 bool WaitForPresentation(
171 const SetupSingleton& setup_singleton,
172 Experiment* experiment,
173 ExperimentStorage* storage,
174 std::unique_ptr<ExperimentStorage::Lock>* storage_lock) {
175 base::TimeDelta retry_delay = GetRetryDelay();
176 bool first_sleep = true;
177 bool loop_again = true;
178
179 do {
180 if (MayShowNotifications() && UserSessionIsNotYoung() &&
181 ActiveWindowIsNotFullscreen()) {
182 return true;
183 }
184
185 // Update the state accordingly if this is the first sleep.
186 if (first_sleep) {
187 experiment->SetState(ExperimentMetrics::kDeferringPresentation);
188 (*storage_lock)->StoreExperiment(*experiment);
189 first_sleep = false;
190 }
191
192 // Release the storage lock and wait on the singleton for five minutes.
193 storage_lock->reset();
194 // Break when another process needs the singleton.
195 loop_again = !setup_singleton.WaitForInterrupt(retry_delay);
196 *storage_lock = storage->AcquireLock();
197 } while (loop_again);
198
199 return false;
200 }
201
202 } // namespace
203
204 // Execution may be in the context of the system or a user on it, and no
205 // guarantee is made regarding the setup singleton.
206 bool ShouldRunUserExperiment() {
207 if (!install_static::kUseGoogleUpdateIntegration)
208 return false;
209
210 if (!install_static::SupportsRetentionExperiments())
211 return false;
212
213 // The current experiment only applies to Windows 10 and newer.
214 if (base::win::GetVersion() < base::win::VERSION_WIN10)
215 return false;
216
217 // Enterprise brand codes and domain joined machines are excluded.
218 if (IsEnterpriseInstall())
219 return false;
220
221 // Gain exclusive access to the persistent experiment state. Only per-install
222 // state may be queried (participation and metrics are okay; Experiment itself
223 // is not).
224 ExperimentStorage storage;
225 auto lock = storage.AcquireLock();
226
227 // Bail out if this install is not selected into the fraction participating in
228 // the current study.
229 // NOTE: No clients will participate while this under development.
Patrick Monette 2017/06/13 19:13:41 Nit: Missing a word?
grt (UTC plus 2) 2017/06/14 20:43:44 Done.
230 if (true || !IsSelectedForStudy(lock.get(), kCurrentStudy))
231 return false;
232
233 // Skip the experiment if a user on the machine has already reached a terminal
234 // state.
235 ExperimentMetrics metrics;
236 if (!lock->LoadMetrics(&metrics) || metrics.InTerminalState())
Patrick Monette 2017/06/13 19:13:41 Should you explicitly check that you are in an ini
grt (UTC plus 2) 2017/06/14 20:43:44 No -- it's okay to pick up where we left off so lo
237 return false;
238
239 return true;
240 }
241
242 // Execution is from the context of the installer immediately following a
243 // successful update. The setup singleton is held.
244 void BeginUserExperiment(const InstallerState& installer_state,
245 const base::FilePath& setup_path,
246 bool user_context) {
247 ExperimentStorage storage;
248
249 // Prepare a command line to relaunch the installed setup.exe for the
250 // experiment.
251 base::CommandLine setup_command(setup_path);
252 InstallUtil::AppendModeSwitch(&setup_command);
253 if (installer_state.system_install())
254 setup_command.AppendSwitch(switches::kSystemLevel);
255 if (installer_state.verbose_logging())
256 setup_command.AppendSwitch(switches::kVerboseLogging);
257 setup_command.AppendSwitch(switches::kUserExperiment);
258 // Copy any test switches used by the spawned process.
259 static constexpr const char* kSwitchesToCopy[] = {
260 kExperimentRetryDelay,
261 };
262 setup_command.CopySwitchesFrom(*base::CommandLine::ForCurrentProcess(),
263 kSwitchesToCopy, arraysize(kSwitchesToCopy));
264
265 if (user_context) {
266 // This is either a per-user install or a per-machine install run via
267 // Active Setup as a normal user.
268 DCHECK(!installer_state.system_install() ||
269 base::GetCurrentProcessIntegrityLevel() == base::MEDIUM_INTEGRITY);
270 VLOG(1) << "Spawning experiment process: "
271 << setup_command.GetCommandLineString();
272 // The installer is already running in the context of an ordinary user.
273 // Relaunch directly to run the experiment.
274 base::LaunchOptions launch_options;
275 launch_options.force_breakaway_from_job_ = true;
276 if (!base::LaunchProcess(setup_command, launch_options).IsValid()) {
277 LOG(ERROR) << __func__
278 << " failed to relaunch installer for user experiment,";
279 WriteInitialState(&storage, ExperimentMetrics::kRelaunchFailed);
280 }
281 return;
282 }
283
284 // The installer is running at high integrity, likely as SYSTEM. Relaunch as
285 // the console user at medium integrity.
286 VLOG(1) << "Attempting to spawn experiment as console user.";
287 if (LaunchSetupAsConsoleUser(setup_command)) {
288 return;
289 }
290
291 // Trigger Active Setup to run on the next user logon if this machine has
292 // never participated in the experiment. This will be done at most once per
293 // machine, even across updates. Doing so more often risks having excessive
294 // active setup activity for some users.
295 auto storage_lock = storage.AcquireLock();
296 ExperimentMetrics experiment_metrics;
297 if (storage_lock->LoadMetrics(&experiment_metrics) &&
298 experiment_metrics.state == ExperimentMetrics::kUninitialized) {
299 UpdateActiveSetupVersionWorkItem item(
300 install_static::GetActiveSetupPath(),
301 UpdateActiveSetupVersionWorkItem::UPDATE_AND_BUMP_SELECTIVE_TRIGGER);
302 if (item.Do()) {
303 VLOG(1) << "Bumped Active Setup Version for user experiment";
304 experiment_metrics.state = ExperimentMetrics::kWaitingForUserLogon;
305 storage_lock->StoreMetrics(experiment_metrics);
306 } else {
307 LOG(ERROR) << "Failed to bump Active Setup Version for user experiment.";
308 }
309 }
310 }
311
312 // This function executes within the context of a signed-in user, even for the
313 // case of system-level installs. In particular, it may be run in a spawned
314 // setup.exe immediately after a successful update or following user logon as a
315 // result of Active Setup.
316 void RunUserExperiment(const base::CommandLine& command_line,
317 const MasterPreferences& master_preferences,
318 InstallationState* original_state,
319 InstallerState* installer_state) {
320 VLOG(1) << __func__;
321
322 ExperimentStorage storage;
323 std::unique_ptr<SetupSingleton> setup_singleton(SetupSingleton::Acquire(
324 command_line, master_preferences, original_state, installer_state));
325 if (!setup_singleton) {
326 VLOG(1) << "Timed out while waiting for setup singleton";
327 WriteInitialState(&storage, ExperimentMetrics::kSingletonWaitTimeout);
328 return;
329 }
330
331 Experiment experiment;
332 auto storage_lock = storage.AcquireLock();
333
334 // Determine the study in which this client participates.
335 ExperimentStorage::Study participation = ExperimentStorage::kNoStudySelected;
336 if (!storage_lock->ReadParticipation(&participation) ||
337 participation == ExperimentStorage::kNoStudySelected) {
338 // ShouldRunUserExperiment should have brought this client into a particular
339 // study. Something is very wrong if it can't be determined here.
340 LOG(ERROR) << "Failed to read study participation.";
341 return;
342 }
343
344 if (!storage_lock->LoadExperiment(&experiment)) {
345 // The metrics correspond to a different user on the machine; nothing to do.
346 VLOG(1) << "Another user is participating in the experiment.";
347 return;
348 }
349
350 // There is nothing to do if the user has already reached a terminal state.
351 if (experiment.metrics().InTerminalState()) {
352 VLOG(1) << "Experiment has reached terminal state: "
353 << experiment.metrics().state;
354 return;
355 }
356
357 // Now the fun begins. Assign this user to a group if this is the first time
358 // through.
359 if (experiment.metrics().InInitialState()) {
360 experiment.AssignGroup(PickGroup(participation));
361 VLOG(1) << "Assigned user to experiment group: "
362 << experiment.metrics().group;
363 }
364
365 // Chrome is considered actively used if it has been run within the last 28
366 // days or if it was installed within the same time period.
367 int days_ago_last_run = GoogleUpdateSettings::GetLastRunTime();
368 if ((days_ago_last_run >= 0 ? days_ago_last_run
369 : GetInstallAge(*installer_state)) <= 28) {
370 VLOG(1) << "Aborting experiment due to activity.";
371 experiment.SetState(ExperimentMetrics::kIsActive);
372 storage_lock->StoreExperiment(experiment);
373 return;
374 }
375
376 // Check for a dormant user: one for which the machine has been off or the
377 // user has been signed out for more than 90% of the last 28 days.
378 if (false) { // TODO(grt): Implement this.
379 VLOG(1) << "Aborting experiment due to dormancy.";
380 experiment.SetState(ExperimentMetrics::kIsDormant);
381 storage_lock->StoreExperiment(experiment);
382 return;
383 }
384
385 if (base::win::IsTabletDevice(nullptr)) {
386 VLOG(1) << "Aborting experiment due to tablet device.";
387 experiment.SetState(ExperimentMetrics::kIsTabletDevice);
388 storage_lock->StoreExperiment(experiment);
389 return;
390 }
391
392 if (IsUpdateRenamePending()) {
393 VLOG(1) << "Aborting experiment due to Chrome update rename pending.";
394 experiment.SetState(ExperimentMetrics::kIsUpdateRenamePending);
395 storage_lock->StoreExperiment(experiment);
396 return;
397 }
398
399 if (!WaitForPresentation(*setup_singleton, &experiment, &storage,
400 &storage_lock)) {
401 VLOG(1) << "Aborting experiment while waiting to present.";
402 experiment.SetState(ExperimentMetrics::kDeferredPresentationAborted);
403 storage_lock->StoreExperiment(experiment);
404 return;
405 }
406
407 VLOG(1) << "Launching Chrome to show the toast.";
408 experiment.SetState(ExperimentMetrics::kLaunchingChrome);
409 storage_lock->StoreExperiment(experiment);
410 LaunchChrome(*installer_state, experiment);
411 }
412
413 // Writes the initial state |state| to the registry if there is no existing
414 // state for this or another user.
415 void WriteInitialState(ExperimentStorage* storage,
416 ExperimentMetrics::State state) {
417 auto storage_lock = storage->AcquireLock();
418
419 // Write the state provided that there is either no existing state or that
420 // any that exists also represents an initial state.
421 ExperimentMetrics experiment_metrics;
422 if (storage_lock->LoadMetrics(&experiment_metrics) &&
423 experiment_metrics.InInitialState()) {
424 experiment_metrics.state = state;
425 storage_lock->StoreMetrics(experiment_metrics);
426 }
427 }
428
429 bool IsEnterpriseBrand() {
430 base::string16 brand;
431
432 if (!GoogleUpdateSettings::GetBrand(&brand))
433 return false;
434
435 if (brand.length() != 4)
436 return false;
437
438 if (brand == L"GGRV")
439 return true;
440
441 return brand[0] == L'G' && brand[1] == L'C' && brand[2] == L'E' &&
442 brand[3] != L'L' && brand[3] >= L'A' && brand[3] <= L'U';
443 }
444
445 bool IsDomainJoined() {
446 LPWSTR buffer = nullptr;
447 NETSETUP_JOIN_STATUS buffer_type = NetSetupUnknownStatus;
448 bool is_joined =
449 ::NetGetJoinInformation(nullptr, &buffer, &buffer_type) == NERR_Success &&
450 buffer_type == NetSetupDomainName;
451 if (buffer)
452 NetApiBufferFree(buffer);
453
454 return is_joined;
455 }
456
457 bool IsSelectedForStudy(ExperimentStorage::Lock* lock,
458 ExperimentStorage::Study current_study) {
459 ExperimentStorage::Study participation = ExperimentStorage::kNoStudySelected;
460 if (!lock->ReadParticipation(&participation))
461 return false;
462
463 participation = HandleParticipationOverride(participation, lock);
464
465 if (participation == ExperimentStorage::kNoStudySelected) {
466 // This install has not been evaluated for participation. Do so now. Select
467 // a small population into the first study of the experiment. Everyone else
468 // gets the second study.
469 participation = base::RandDouble() <= 0.02756962532
Patrick Monette 2017/06/13 19:13:41 Why is this not 0.025?
grt (UTC plus 2) 2017/06/14 20:43:44 This is the value we reached via maths in a doc.
470 ? ExperimentStorage::kStudyOne
471 : ExperimentStorage::kStudyTwo;
472 if (!lock->WriteParticipation(participation))
473 return false;
474 }
475
476 return participation <= current_study;
477 }
478
479 int PickGroup(ExperimentStorage::Study participation) {
480 DCHECK(participation == ExperimentStorage::kStudyOne ||
481 participation == ExperimentStorage::kStudyTwo);
482 static constexpr int kHoldbackGroup = ExperimentMetrics::kNumGroups - 1;
483
484 if (participation == ExperimentStorage::kStudyOne) {
485 // Evenly distrubute clients among the groups.
486 return base::RandInt(0, ExperimentMetrics::kNumGroups - 1);
487 }
488
489 // 1% holdback, 99% in the winning group.
490 return base::RandDouble() < 0.01 ? kHoldbackGroup : kStudyTwoGroup;
Patrick Monette 2017/06/13 19:13:41 Why split non-participating (participation != Expe
grt (UTC plus 2) 2017/06/14 20:43:44 The holdback group is the group that participates
491 }
492
493 bool IsUpdateRenamePending() {
494 // Consider an update to be pending if an "opv" value is present in the
495 // registry or if Chrome's version as registered with Omaha doesn't match the
496 // current version.
497 base::string16 clients_key_path =
498 install_static::GetClientsKeyPath(install_static::GetAppGuid());
499 const HKEY root = install_static::IsSystemInstall() ? HKEY_LOCAL_MACHINE
500 : HKEY_CURRENT_USER;
501 base::win::RegKey clients_key;
502
503 // The failure modes below are generally indicitive of a run from a
504 // non-installed Chrome. Pretend that all is well.
505 if (clients_key.Open(root, clients_key_path.c_str(),
506 KEY_WOW64_64KEY | KEY_QUERY_VALUE) != ERROR_SUCCESS) {
507 return false;
508 }
509 if (clients_key.HasValue(google_update::kRegOldVersionField))
510 return true;
511 base::string16 product_version;
512 if (clients_key.ReadValue(google_update::kRegVersionField,
513 &product_version) != ERROR_SUCCESS) {
514 return false;
515 }
516 return product_version != TEXT(CHROME_VERSION_STRING);
517 }
518
519 void LaunchChrome(const InstallerState& installer_state,
520 const Experiment& experiment) {
521 const base::FilePath chrome_exe =
522 installer_state.target_path().Append(kChromeExe);
523 base::CommandLine command_line(chrome_exe);
524 command_line.AppendSwitchNative(::switches::kTryChromeAgain,
525 base::IntToString16(experiment.group()));
526
527 STARTUPINFOW startup_info = {sizeof(startup_info)};
528 PROCESS_INFORMATION temp_process_info = {};
529 base::string16 writable_command_line_string(
530 command_line.GetCommandLineString());
531 if (!::CreateProcess(
532 chrome_exe.value().c_str(), &writable_command_line_string[0],
533 nullptr /* lpProcessAttributes */, nullptr /* lpThreadAttributes */,
534 FALSE /* bInheritHandles */, CREATE_NO_WINDOW,
535 nullptr /* lpEnvironment */, nullptr /* lpCurrentDirectory */,
536 &startup_info, &temp_process_info)) {
537 PLOG(ERROR) << "Failed to launch: " << writable_command_line_string;
538 return;
539 }
540
541 base::win::ScopedProcessInformation process_info(temp_process_info);
542 }
543
544 } // namespace installer
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698