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/attrition_experiments.h"
24 #include "chrome/common/chrome_paths.h"
25 #include "chrome/common/chrome_result_codes.h"
26 #include "chrome/common/chrome_switches.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 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
);
279 CloseHandle((HANDLE
) reg_key_handle
);
282 GoogleUpdateSettings::SetClient(experiment_group
);
288 bool CreateExperimentDetails(int flavor
, ExperimentDetails
* experiment
) {
289 struct FlavorDetails
{
293 // Maximum number of experiment flavors we support.
294 static const int kMax
= 4;
295 // This struct determines which experiment flavors we show for each locale and
298 // Plugin infobar experiment:
299 // The experiment in 2011 used PIxx codes.
301 // Inactive user toast experiment:
302 // The experiment in Dec 2009 used TGxx and THxx.
303 // The experiment in Feb 2010 used TKxx and TLxx.
304 // The experiment in Apr 2010 used TMxx and TNxx.
305 // The experiment in Oct 2010 used TVxx TWxx TXxx TYxx.
306 // The experiment in Feb 2011 used SJxx SKxx SLxx SMxx.
307 // The experiment in Mar 2012 used ZAxx ZBxx ZCxx.
308 // The experiment in Jan 2013 uses DAxx.
309 using namespace attrition_experiments
;
311 static const struct UserExperimentSpecs
{
312 const wchar_t* locale
; // Locale to show this experiment for (* for all).
313 const wchar_t* brands
; // Brand codes show this experiment for (* for all).
314 int control_group
; // Size of the control group, in percentages.
315 const wchar_t* prefix
; // The two letter experiment code. The second letter
316 // will be incremented with the flavor.
317 FlavorDetails flavors
[kMax
];
319 // The first match from top to bottom is used so this list should be ordered
320 // most-specific rule first.
321 { L
"*", L
"GGRV", // All locales, GGRV is enterprise.
322 0, // 0 percent control group.
323 L
"EA", // Experiment is EAxx, EBxx, etc.
324 // No flavors means no experiment.
331 { L
"*", L
"*", // All locales, all brands.
332 5, // 5 percent control group.
333 L
"DA", // Experiment is DAxx.
334 // One single flavor.
335 { { IDS_TRY_TOAST_HEADING3
, kToastUiMakeDefault
},
343 base::string16 locale
;
344 GoogleUpdateSettings::GetLanguage(&locale
);
345 if (locale
.empty() || (locale
== L
"en"))
348 base::string16 brand
;
349 if (!GoogleUpdateSettings::GetBrand(&brand
))
350 brand
.clear(); // Could still be viable for catch-all rules
352 for (int i
= 0; i
< arraysize(kExperiments
); ++i
) {
353 base::string16 experiment_locale
= kExperiments
[i
].locale
;
354 if (experiment_locale
!= locale
&& experiment_locale
!= L
"*")
357 std::vector
<base::string16
> brand_codes
;
358 base::SplitString(kExperiments
[i
].brands
, L
',', &brand_codes
);
359 if (brand_codes
.empty())
361 for (std::vector
<base::string16
>::iterator it
= brand_codes
.begin();
362 it
!= brand_codes
.end(); ++it
) {
363 if (*it
!= brand
&& *it
!= L
"*")
365 // We have found our match.
366 const UserExperimentSpecs
& match
= kExperiments
[i
];
367 // Find out how many flavors we have. Zero means no experiment.
369 while (match
.flavors
[num_flavors
].heading_id
) { ++num_flavors
; }
374 flavor
= base::RandInt(0, num_flavors
- 1);
375 experiment
->flavor
= flavor
;
376 experiment
->heading
= match
.flavors
[flavor
].heading_id
;
377 experiment
->control_group
= match
.control_group
;
378 const wchar_t prefix
[] = { match
.prefix
[0], match
.prefix
[1] + flavor
, 0 };
379 experiment
->prefix
= prefix
;
380 experiment
->flags
= match
.flavors
[flavor
].flags
;
388 // Currently we only have one experiment: the inactive user toast. Which only
389 // applies for users doing upgrades.
391 // There are three scenarios when this function is called:
392 // 1- Is a per-user-install and it updated: perform the experiment
393 // 2- Is a system-install and it updated : relaunch as the interactive user
394 // 3- It has been re-launched from the #2 case. In this case we enter
395 // this function with |system_install| true and a REENTRY_SYS_UPDATE status.
396 void LaunchBrowserUserExperiment(const base::CommandLine
& base_cmd_line
,
397 InstallStatus status
,
400 if (NEW_VERSION_UPDATED
== status
) {
401 base::CommandLine
cmd_line(base_cmd_line
);
402 cmd_line
.AppendSwitch(switches::kSystemLevelToast
);
403 // We need to relaunch as the interactive user.
404 LaunchSetupAsConsoleUser(&cmd_line
);
408 if (status
!= NEW_VERSION_UPDATED
&& status
!= REENTRY_SYS_UPDATE
) {
409 // We are not updating or in re-launch. Exit.
414 // The |flavor| value ends up being processed by TryChromeDialogView to show
415 // different experiments.
416 ExperimentDetails experiment
;
417 if (!CreateExperimentDetails(-1, &experiment
)) {
418 VLOG(1) << "Failed to get experiment details.";
421 int flavor
= experiment
.flavor
;
422 base::string16 base_group
= experiment
.prefix
;
424 base::string16 brand
;
425 if (GoogleUpdateSettings::GetBrand(&brand
) && (brand
== L
"CHXX")) {
426 // Testing only: the user automatically qualifies for the experiment.
427 VLOG(1) << "Experiment qualification bypass";
429 // Check that the user was not already drafted in this experiment.
430 base::string16 client
;
431 GoogleUpdateSettings::GetClient(&client
);
432 if (client
.size() > 2) {
433 if (base_group
== client
.substr(0, 2)) {
434 VLOG(1) << "User already participated in this experiment";
438 const bool experiment_enabled
= false;
439 if (!experiment_enabled
) {
440 VLOG(1) << "Toast experiment is disabled.";
444 // Check browser usage inactivity by the age of the last-write time of the
445 // relevant chrome user data directory.
446 const int kThirtyDays
= 30 * 24;
447 const int dir_age_hours
= GetUserDataDirectoryWriteAgeInHours();
448 if (dir_age_hours
< 0) {
449 // This means that we failed to find the user data dir. The most likely
450 // cause is that this user has not ever used chrome at all which can
451 // happen in a system-level install.
452 SetClient(base_group
+ kToastUDDirFailure
, true);
454 } else if (dir_age_hours
< kThirtyDays
) {
455 // An active user, so it does not qualify.
456 VLOG(1) << "Chrome used in last " << dir_age_hours
<< " hours";
457 SetClient(base_group
+ kToastActiveGroup
, true);
460 // Check to see if this user belongs to the control group.
461 double control_group
= 1.0 * (100 - experiment
.control_group
) / 100;
462 if (base::RandDouble() > control_group
) {
463 SetClient(base_group
+ kToastExpControlGroup
, true);
464 VLOG(1) << "User is control group";
469 VLOG(1) << "User drafted for toast experiment " << flavor
;
470 SetClient(base_group
+ kToastExpBaseGroup
, false);
471 // User level: The experiment needs to be performed in a different process
472 // because google_update expects the upgrade process to be quick and nimble.
473 // System level: We have already been relaunched, so we don't need to be
474 // quick, but we relaunch to follow the exact same codepath.
475 base::CommandLine
cmd_line(base_cmd_line
);
476 cmd_line
.AppendSwitchASCII(switches::kInactiveUserToast
,
477 base::IntToString(flavor
));
478 cmd_line
.AppendSwitchASCII(switches::kExperimentGroup
,
479 base::UTF16ToASCII(base_group
));
480 LaunchSetup(&cmd_line
, system_level
);
483 // User qualifies for the experiment. To test, use --try-chrome-again=|flavor|
484 // as a parameter to chrome.exe.
485 void InactiveUserToastExperiment(int flavor
,
486 const base::string16
& experiment_group
,
487 const Product
& product
,
488 const base::FilePath
& application_path
) {
489 // Add the 'welcome back' url for chrome to show.
490 base::CommandLine
options(base::CommandLine::NO_PROGRAM
);
491 options
.AppendSwitchNative(::switches::kTryChromeAgain
,
492 base::IntToString16(flavor
));
493 // Prepend the url with a space.
494 base::string16
url(GetWelcomeBackUrl());
495 options
.AppendArg("--");
496 options
.AppendArgNative(url
);
497 // The command line should now have the url added as:
498 // "chrome.exe -- <url>"
499 DCHECK_NE(base::string16::npos
,
500 options
.GetCommandLineString().find(L
" -- " + url
));
502 // Launch chrome now. It will show the toast UI.
504 if (!product
.LaunchChromeAndWait(application_path
, options
, &exit_code
))
507 // The chrome process has exited, figure out what happened.
508 const wchar_t* outcome
= NULL
;
510 case content::RESULT_CODE_NORMAL_EXIT
:
511 outcome
= kToastExpTriesOkGroup
;
513 case chrome::RESULT_CODE_NORMAL_EXIT_CANCEL
:
514 outcome
= kToastExpCancelGroup
;
516 case chrome::RESULT_CODE_NORMAL_EXIT_EXP2
:
517 outcome
= kToastExpUninstallGroup
;
520 outcome
= kToastExpTriesErrorGroup
;
522 // Write to the |client| key for the last time.
523 SetClient(experiment_group
+ outcome
, true);
525 if (outcome
!= kToastExpUninstallGroup
)
527 // The user wants to uninstall. This is a best effort operation. Note that
528 // we waited for chrome to exit so the uninstall would not detect chrome
530 bool system_level_toast
= base::CommandLine::ForCurrentProcess()->HasSwitch(
531 switches::kSystemLevelToast
);
533 base::CommandLine
cmd(InstallUtil::GetChromeUninstallCmd(
534 system_level_toast
, product
.distribution()->GetType()));
535 base::LaunchProcess(cmd
, base::LaunchOptions());
538 } // namespace installer