1 // Copyright 2013 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.
5 #include "chrome/installer/util/user_experiment.h"
12 #include "base/command_line.h"
13 #include "base/files/file_path.h"
14 #include "base/path_service.h"
15 #include "base/process/launch.h"
16 #include "base/rand_util.h"
17 #include "base/strings/string_number_conversions.h"
18 #include "base/strings/string_split.h"
19 #include "base/strings/string_util.h"
20 #include "base/strings/utf_string_conversions.h"
21 #include "base/win/scoped_handle.h"
22 #include "base/win/windows_version.h"
23 #include "chrome/common/chrome_paths.h"
24 #include "chrome/common/chrome_result_codes.h"
25 #include "chrome/common/chrome_switches.h"
26 #include "chrome/grit/chromium_strings.h"
27 #include "chrome/installer/util/browser_distribution.h"
28 #include "chrome/installer/util/google_update_constants.h"
29 #include "chrome/installer/util/google_update_settings.h"
30 #include "chrome/installer/util/helper.h"
31 #include "chrome/installer/util/install_util.h"
32 #include "chrome/installer/util/product.h"
33 #include "content/public/common/result_codes.h"
35 #pragma comment(lib, "wtsapi32.lib")
41 // The following strings are the possible outcomes of the toast experiment
42 // as recorded in the |client| field.
43 const wchar_t kToastExpControlGroup
[] = L
"01";
44 const wchar_t kToastExpCancelGroup
[] = L
"02";
45 const wchar_t kToastExpUninstallGroup
[] = L
"04";
46 const wchar_t kToastExpTriesOkGroup
[] = L
"18";
47 const wchar_t kToastExpTriesErrorGroup
[] = L
"28";
48 const wchar_t kToastActiveGroup
[] = L
"40";
49 const wchar_t kToastUDDirFailure
[] = L
"40";
50 const wchar_t kToastExpBaseGroup
[] = L
"80";
52 // Substitute the locale parameter in uninstall URL with whatever
53 // Google Update tells us is the locale. In case we fail to find
54 // the locale, we use US English.
55 base::string16
LocalizeUrl(const wchar_t* url
) {
56 base::string16 language
;
57 if (!GoogleUpdateSettings::GetLanguage(&language
))
58 language
= L
"en-US"; // Default to US English.
59 return base::ReplaceStringPlaceholders(url
, language
.c_str(), NULL
);
62 base::string16
GetWelcomeBackUrl() {
63 const wchar_t kWelcomeUrl
[] = L
"http://www.google.com/chrome/intl/$1/"
64 L
"welcomeback-new.html";
65 return LocalizeUrl(kWelcomeUrl
);
68 // Converts FILETIME to hours. FILETIME times are absolute times in
69 // 100 nanosecond units. For example 5:30 pm of June 15, 2009 is 3580464.
70 int FileTimeToHours(const FILETIME
& time
) {
71 const ULONGLONG k100sNanoSecsToHours
= 10000000LL * 60 * 60;
72 ULARGE_INTEGER uli
= {{time
.dwLowDateTime
, time
.dwHighDateTime
}};
73 return static_cast<int>(uli
.QuadPart
/ k100sNanoSecsToHours
);
76 // Returns the directory last write time in hours since January 1, 1601.
77 // Returns -1 if there was an error retrieving the directory time.
78 int GetDirectoryWriteTimeInHours(const wchar_t* path
) {
79 // To open a directory you need to pass FILE_FLAG_BACKUP_SEMANTICS.
80 DWORD share
= FILE_SHARE_READ
| FILE_SHARE_WRITE
| FILE_SHARE_DELETE
;
81 base::win::ScopedHandle
file(::CreateFileW(path
, 0, share
, NULL
,
82 OPEN_EXISTING
, FILE_FLAG_BACKUP_SEMANTICS
, NULL
));
87 return ::GetFileTime(file
.Get(), NULL
, NULL
, &time
) ?
88 FileTimeToHours(time
) : -1;
91 // Returns the time in hours since the last write to the user data directory.
92 // A return value of 14 means that the directory was last written 14 hours ago.
93 // Returns -1 if there was an error retrieving the directory.
94 int GetUserDataDirectoryWriteAgeInHours() {
95 base::FilePath user_data_dir
;
96 if (!PathService::Get(chrome::DIR_USER_DATA
, &user_data_dir
))
98 int dir_time
= GetDirectoryWriteTimeInHours(user_data_dir
.value().c_str());
102 GetSystemTimeAsFileTime(&time
);
103 int now_time
= FileTimeToHours(time
);
104 if (dir_time
>= now_time
)
106 return (now_time
- dir_time
);
109 // Launches setup.exe (located at |setup_path|) with |cmd_line|.
110 // If system_level_toast is true, appends --system-level-toast.
111 // If handle to experiment result key was given at startup, re-add it.
112 // Does not wait for the process to terminate.
113 // |cmd_line| may be modified as a result of this call.
114 bool LaunchSetup(base::CommandLine
* cmd_line
, bool system_level_toast
) {
115 const base::CommandLine
& current_cmd_line
=
116 *base::CommandLine::ForCurrentProcess();
118 // Propagate --verbose-logging to the invoked setup.exe.
119 if (current_cmd_line
.HasSwitch(switches::kVerboseLogging
))
120 cmd_line
->AppendSwitch(switches::kVerboseLogging
);
122 // Re-add the system level toast flag.
123 if (system_level_toast
) {
124 cmd_line
->AppendSwitch(switches::kSystemLevel
);
125 cmd_line
->AppendSwitch(switches::kSystemLevelToast
);
127 // Re-add the toast result key. We need to do this because Setup running as
128 // system passes the key to Setup running as user, but that child process
129 // does not perform the actual toasting, it launches another Setup (as user)
130 // to do so. That is the process that needs the key.
131 std::string
key(switches::kToastResultsKey
);
132 std::string toast_key
= current_cmd_line
.GetSwitchValueASCII(key
);
133 if (!toast_key
.empty()) {
134 cmd_line
->AppendSwitchASCII(key
, toast_key
);
136 // Use handle inheritance to make sure the duplicated toast results key
137 // gets inherited by the child process.
138 base::LaunchOptions options
;
139 options
.inherit_handles
= true;
140 base::Process process
= base::LaunchProcess(*cmd_line
, options
);
141 return process
.IsValid();
145 base::Process process
= base::LaunchProcess(*cmd_line
, base::LaunchOptions());
146 return process
.IsValid();
149 // For System level installs, setup.exe lives in the system temp, which
150 // is normally c:\windows\temp. In many cases files inside this folder
151 // are not accessible for execution by regular user accounts.
152 // This function changes the permissions so that any authenticated user
153 // can launch |exe| later on. This function should only be called if the
154 // code is running at the system level.
155 bool FixDACLsForExecute(const base::FilePath
& exe
) {
156 // The general strategy to is to add an ACE to the exe DACL the quick
157 // and dirty way: a) read the DACL b) convert it to sddl string c) add the
158 // new ACE to the string d) convert sddl string back to DACL and finally
159 // e) write new dacl.
161 DWORD len
= sizeof(buff
);
162 PSECURITY_DESCRIPTOR sd
= reinterpret_cast<PSECURITY_DESCRIPTOR
>(buff
);
163 if (!::GetFileSecurityW(exe
.value().c_str(), DACL_SECURITY_INFORMATION
,
168 if (!::ConvertSecurityDescriptorToStringSecurityDescriptorW(sd
,
169 SDDL_REVISION_1
, DACL_SECURITY_INFORMATION
, &sddl
, NULL
))
171 base::string16
new_sddl(sddl
);
174 // See MSDN for the security descriptor definition language (SDDL) syntax,
175 // in our case we add "A;" generic read 'GR' and generic execute 'GX' for
176 // the nt\authenticated_users 'AU' group, that becomes:
177 const wchar_t kAllowACE
[] = L
"(A;;GRGX;;;AU)";
178 // We should check that there are no special ACES for the group we
179 // are interested, which is nt\authenticated_users.
180 if (base::string16::npos
!= new_sddl
.find(L
";AU)"))
182 // Specific ACEs (not inherited) need to go to the front. It is ok if we
183 // are the very first one.
184 size_t pos_insert
= new_sddl
.find(L
"(");
185 if (base::string16::npos
== pos_insert
)
187 // All good, time to change the dacl.
188 new_sddl
.insert(pos_insert
, kAllowACE
);
189 if (!::ConvertStringSecurityDescriptorToSecurityDescriptorW(new_sddl
.c_str(),
190 SDDL_REVISION_1
, &sd
, NULL
))
192 bool rv
= ::SetFileSecurityW(exe
.value().c_str(), DACL_SECURITY_INFORMATION
,
198 // This function launches setup as the currently logged-in interactive
199 // user that is the user whose logon session is attached to winsta0\default.
200 // It assumes that currently we are running as SYSTEM in a non-interactive
202 // The function fails if there is no interactive session active, basically
203 // the computer is on but nobody has logged in locally.
204 // Remote Desktop sessions do not count as interactive sessions; running this
205 // method as a user logged in via remote desktop will do nothing.
206 bool LaunchSetupAsConsoleUser(base::CommandLine
* cmd_line
) {
207 // Convey to the invoked setup.exe that it's operating on a system-level
209 cmd_line
->AppendSwitch(switches::kSystemLevel
);
211 // Propagate --verbose-logging to the invoked setup.exe.
212 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
213 switches::kVerboseLogging
))
214 cmd_line
->AppendSwitch(switches::kVerboseLogging
);
216 // Get the Google Update results key, and pass it on the command line to
217 // the child process.
218 int key
= GoogleUpdateSettings::DuplicateGoogleUpdateSystemClientKey();
219 cmd_line
->AppendSwitchASCII(switches::kToastResultsKey
,
220 base::IntToString(key
));
222 if (base::win::GetVersion() > base::win::VERSION_XP
) {
223 // Make sure that in Vista and Above we have the proper DACLs so
224 // the interactive user can launch it.
225 if (!FixDACLsForExecute(cmd_line
->GetProgram()))
229 DWORD console_id
= ::WTSGetActiveConsoleSessionId();
230 if (console_id
== 0xFFFFFFFF) {
231 PLOG(ERROR
) << __FUNCTION__
<< " failed to get active session id";
235 if (!::WTSQueryUserToken(console_id
, &user_token
)) {
236 PLOG(ERROR
) << __FUNCTION__
<< " failed to get user token for console_id "
240 // Note: Handle inheritance must be true in order for the child process to be
241 // able to use the duplicated handle above (Google Update results).
242 base::LaunchOptions options
;
243 options
.as_user
= user_token
;
244 options
.inherit_handles
= true;
245 options
.empty_desktop_name
= true;
246 VLOG(1) << __FUNCTION__
<< " launching " << cmd_line
->GetCommandLineString();
247 base::Process process
= base::LaunchProcess(*cmd_line
, options
);
248 ::CloseHandle(user_token
);
249 VLOG(1) << __FUNCTION__
<< " result: " << process
.IsValid();
250 return process
.IsValid();
253 // A helper function that writes to HKLM if the handle was passed through the
254 // command line, but HKCU otherwise. |experiment_group| is the value to write
255 // and |last_write| is used when writing to HKLM to determine whether to close
256 // the handle when done.
257 void SetClient(const base::string16
& experiment_group
, bool last_write
) {
258 static int reg_key_handle
= -1;
259 if (reg_key_handle
== -1) {
260 // If a specific Toast Results key handle (presumably to our HKLM key) was
261 // passed in to the command line (such as for system level installs), we use
262 // it. Otherwise, we write to the key under HKCU.
263 const base::CommandLine
& cmd_line
= *base::CommandLine::ForCurrentProcess();
264 if (cmd_line
.HasSwitch(switches::kToastResultsKey
)) {
265 // Get the handle to the key under HKLM.
267 cmd_line
.GetSwitchValueNative(switches::kToastResultsKey
),
274 if (reg_key_handle
) {
275 // Use it to write the experiment results.
276 GoogleUpdateSettings::WriteGoogleUpdateSystemClientKey(
277 reg_key_handle
, google_update::kRegClientField
, experiment_group
);
280 reinterpret_cast<HANDLE
>(static_cast<uintptr_t>(reg_key_handle
)));
284 GoogleUpdateSettings::SetClient(experiment_group
);
290 bool CreateExperimentDetails(int flavor
, ExperimentDetails
* experiment
) {
291 struct FlavorDetails
{
295 // Maximum number of experiment flavors we support.
296 static const int kMax
= 4;
297 // This struct determines which experiment flavors we show for each locale and
300 // Plugin infobar experiment:
301 // The experiment in 2011 used PIxx codes.
303 // Inactive user toast experiment:
304 // The experiment in Dec 2009 used TGxx and THxx.
305 // The experiment in Feb 2010 used TKxx and TLxx.
306 // The experiment in Apr 2010 used TMxx and TNxx.
307 // The experiment in Oct 2010 used TVxx TWxx TXxx TYxx.
308 // The experiment in Feb 2011 used SJxx SKxx SLxx SMxx.
309 // The experiment in Mar 2012 used ZAxx ZBxx ZCxx.
310 // The experiment in Jan 2013 uses DAxx.
312 static const struct UserExperimentSpecs
{
313 const wchar_t* locale
; // Locale to show this experiment for (* for all).
314 const wchar_t* brands
; // Brand codes show this experiment for (* for all).
315 int control_group
; // Size of the control group, in percentages.
316 const wchar_t* prefix
; // The two letter experiment code. The second letter
317 // will be incremented with the flavor.
318 FlavorDetails flavors
[kMax
];
320 // The first match from top to bottom is used so this list should be ordered
321 // most-specific rule first.
322 { L
"*", L
"GGRV", // All locales, GGRV is enterprise.
323 0, // 0 percent control group.
324 L
"EA", // Experiment is EAxx, EBxx, etc.
325 // No flavors means no experiment.
332 { L
"*", L
"*", // All locales, all brands.
333 5, // 5 percent control group.
334 L
"DA", // Experiment is DAxx.
335 // One single flavor.
336 { { IDS_TRY_TOAST_HEADING3
, kToastUiMakeDefault
},
344 base::string16 locale
;
345 GoogleUpdateSettings::GetLanguage(&locale
);
346 if (locale
.empty() || (locale
== L
"en"))
349 base::string16 brand
;
350 if (!GoogleUpdateSettings::GetBrand(&brand
))
351 brand
.clear(); // Could still be viable for catch-all rules
353 for (int i
= 0; i
< arraysize(kExperiments
); ++i
) {
354 base::string16 experiment_locale
= kExperiments
[i
].locale
;
355 if (experiment_locale
!= locale
&& experiment_locale
!= L
"*")
358 for (const base::string16
& cur
: base::SplitString(
359 kExperiments
[i
].brands
, L
",",
360 base::TRIM_WHITESPACE
, base::SPLIT_WANT_ALL
)) {
361 if (cur
!= brand
&& cur
!= L
"*")
363 // We have found our match.
364 const UserExperimentSpecs
& match
= kExperiments
[i
];
365 // Find out how many flavors we have. Zero means no experiment.
367 while (match
.flavors
[num_flavors
].heading_id
) { ++num_flavors
; }
372 flavor
= base::RandInt(0, num_flavors
- 1);
373 experiment
->flavor
= flavor
;
374 experiment
->heading
= match
.flavors
[flavor
].heading_id
;
375 experiment
->control_group
= match
.control_group
;
376 const wchar_t prefix
[] = {
377 match
.prefix
[0], static_cast<wchar_t>(match
.prefix
[1] + flavor
), 0};
378 experiment
->prefix
= prefix
;
379 experiment
->flags
= match
.flavors
[flavor
].flags
;
387 // Currently we only have one experiment: the inactive user toast. Which only
388 // applies for users doing upgrades.
390 // There are three scenarios when this function is called:
391 // 1- Is a per-user-install and it updated: perform the experiment
392 // 2- Is a system-install and it updated : relaunch as the interactive user
393 // 3- It has been re-launched from the #2 case. In this case we enter
394 // this function with |system_install| true and a REENTRY_SYS_UPDATE status.
395 void LaunchBrowserUserExperiment(const base::CommandLine
& base_cmd_line
,
396 InstallStatus status
,
399 if (NEW_VERSION_UPDATED
== status
) {
400 base::CommandLine
cmd_line(base_cmd_line
);
401 cmd_line
.AppendSwitch(switches::kSystemLevelToast
);
402 // We need to relaunch as the interactive user.
403 LaunchSetupAsConsoleUser(&cmd_line
);
407 if (status
!= NEW_VERSION_UPDATED
&& status
!= REENTRY_SYS_UPDATE
) {
408 // We are not updating or in re-launch. Exit.
413 // The |flavor| value ends up being processed by TryChromeDialogView to show
414 // different experiments.
415 ExperimentDetails experiment
;
416 if (!CreateExperimentDetails(-1, &experiment
)) {
417 VLOG(1) << "Failed to get experiment details.";
420 int flavor
= experiment
.flavor
;
421 base::string16 base_group
= experiment
.prefix
;
423 base::string16 brand
;
424 if (GoogleUpdateSettings::GetBrand(&brand
) && (brand
== L
"CHXX")) {
425 // Testing only: the user automatically qualifies for the experiment.
426 VLOG(1) << "Experiment qualification bypass";
428 // Check that the user was not already drafted in this experiment.
429 base::string16 client
;
430 GoogleUpdateSettings::GetClient(&client
);
431 if (client
.size() > 2) {
432 if (base_group
== client
.substr(0, 2)) {
433 VLOG(1) << "User already participated in this experiment";
437 const bool experiment_enabled
= false;
438 if (!experiment_enabled
) {
439 VLOG(1) << "Toast experiment is disabled.";
443 // Check browser usage inactivity by the age of the last-write time of the
444 // relevant chrome user data directory.
445 const int kThirtyDays
= 30 * 24;
446 const int dir_age_hours
= GetUserDataDirectoryWriteAgeInHours();
447 if (dir_age_hours
< 0) {
448 // This means that we failed to find the user data dir. The most likely
449 // cause is that this user has not ever used chrome at all which can
450 // happen in a system-level install.
451 SetClient(base_group
+ kToastUDDirFailure
, true);
453 } else if (dir_age_hours
< kThirtyDays
) {
454 // An active user, so it does not qualify.
455 VLOG(1) << "Chrome used in last " << dir_age_hours
<< " hours";
456 SetClient(base_group
+ kToastActiveGroup
, true);
459 // Check to see if this user belongs to the control group.
460 double control_group
= 1.0 * (100 - experiment
.control_group
) / 100;
461 if (base::RandDouble() > control_group
) {
462 SetClient(base_group
+ kToastExpControlGroup
, true);
463 VLOG(1) << "User is control group";
468 VLOG(1) << "User drafted for toast experiment " << flavor
;
469 SetClient(base_group
+ kToastExpBaseGroup
, false);
470 // User level: The experiment needs to be performed in a different process
471 // because google_update expects the upgrade process to be quick and nimble.
472 // System level: We have already been relaunched, so we don't need to be
473 // quick, but we relaunch to follow the exact same codepath.
474 base::CommandLine
cmd_line(base_cmd_line
);
475 cmd_line
.AppendSwitchASCII(switches::kInactiveUserToast
,
476 base::IntToString(flavor
));
477 cmd_line
.AppendSwitchASCII(switches::kExperimentGroup
,
478 base::UTF16ToASCII(base_group
));
479 LaunchSetup(&cmd_line
, system_level
);
482 // User qualifies for the experiment. To test, use --try-chrome-again=|flavor|
483 // as a parameter to chrome.exe.
484 void InactiveUserToastExperiment(int flavor
,
485 const base::string16
& experiment_group
,
486 const Product
& product
,
487 const base::FilePath
& application_path
) {
488 // Add the 'welcome back' url for chrome to show.
489 base::CommandLine
options(base::CommandLine::NO_PROGRAM
);
490 options
.AppendSwitchNative(::switches::kTryChromeAgain
,
491 base::IntToString16(flavor
));
492 // Prepend the url with a space.
493 base::string16
url(GetWelcomeBackUrl());
494 options
.AppendArg("--");
495 options
.AppendArgNative(url
);
496 // The command line should now have the url added as:
497 // "chrome.exe -- <url>"
498 DCHECK_NE(base::string16::npos
,
499 options
.GetCommandLineString().find(L
" -- " + url
));
501 // Launch chrome now. It will show the toast UI.
503 if (!product
.LaunchChromeAndWait(application_path
, options
, &exit_code
))
506 // The chrome process has exited, figure out what happened.
507 const wchar_t* outcome
= NULL
;
509 case content::RESULT_CODE_NORMAL_EXIT
:
510 outcome
= kToastExpTriesOkGroup
;
512 case chrome::RESULT_CODE_NORMAL_EXIT_CANCEL
:
513 outcome
= kToastExpCancelGroup
;
515 case chrome::RESULT_CODE_NORMAL_EXIT_EXP2
:
516 outcome
= kToastExpUninstallGroup
;
519 outcome
= kToastExpTriesErrorGroup
;
521 // Write to the |client| key for the last time.
522 SetClient(experiment_group
+ outcome
, true);
524 if (outcome
!= kToastExpUninstallGroup
)
526 // The user wants to uninstall. This is a best effort operation. Note that
527 // we waited for chrome to exit so the uninstall would not detect chrome
529 bool system_level_toast
= base::CommandLine::ForCurrentProcess()->HasSwitch(
530 switches::kSystemLevelToast
);
532 base::CommandLine
cmd(InstallUtil::GetChromeUninstallCmd(
533 system_level_toast
, product
.distribution()->GetType()));
534 base::LaunchProcess(cmd
, base::LaunchOptions());
537 } // namespace installer