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(CommandLine* cmd_line, bool system_level_toast) {
115 const CommandLine& current_cmd_line = *CommandLine::ForCurrentProcess();
117 // Propagate --verbose-logging to the invoked setup.exe.
118 if (current_cmd_line.HasSwitch(switches::kVerboseLogging))
119 cmd_line->AppendSwitch(switches::kVerboseLogging);
121 // Re-add the system level toast flag.
122 if (system_level_toast) {
123 cmd_line->AppendSwitch(switches::kSystemLevel);
124 cmd_line->AppendSwitch(switches::kSystemLevelToast);
126 // Re-add the toast result key. We need to do this because Setup running as
127 // system passes the key to Setup running as user, but that child process
128 // does not perform the actual toasting, it launches another Setup (as user)
129 // to do so. That is the process that needs the key.
130 std::string key(switches::kToastResultsKey);
131 std::string toast_key = current_cmd_line.GetSwitchValueASCII(key);
132 if (!toast_key.empty()) {
133 cmd_line->AppendSwitchASCII(key, toast_key);
135 // Use handle inheritance to make sure the duplicated toast results key
136 // gets inherited by the child process.
137 base::LaunchOptions options;
138 options.inherit_handles = true;
139 return base::LaunchProcess(*cmd_line, options, NULL);
143 return base::LaunchProcess(*cmd_line, base::LaunchOptions(), NULL);
146 // For System level installs, setup.exe lives in the system temp, which
147 // is normally c:\windows\temp. In many cases files inside this folder
148 // are not accessible for execution by regular user accounts.
149 // This function changes the permissions so that any authenticated user
150 // can launch |exe| later on. This function should only be called if the
151 // code is running at the system level.
152 bool FixDACLsForExecute(const base::FilePath& exe) {
153 // The general strategy to is to add an ACE to the exe DACL the quick
154 // and dirty way: a) read the DACL b) convert it to sddl string c) add the
155 // new ACE to the string d) convert sddl string back to DACL and finally
156 // e) write new dacl.
158 DWORD len = sizeof(buff);
159 PSECURITY_DESCRIPTOR sd = reinterpret_cast<PSECURITY_DESCRIPTOR>(buff);
160 if (!::GetFileSecurityW(exe.value().c_str(), DACL_SECURITY_INFORMATION,
165 if (!::ConvertSecurityDescriptorToStringSecurityDescriptorW(sd,
166 SDDL_REVISION_1, DACL_SECURITY_INFORMATION, &sddl, NULL))
168 base::string16 new_sddl(sddl);
171 // See MSDN for the security descriptor definition language (SDDL) syntax,
172 // in our case we add "A;" generic read 'GR' and generic execute 'GX' for
173 // the nt\authenticated_users 'AU' group, that becomes:
174 const wchar_t kAllowACE[] = L"(A;;GRGX;;;AU)";
175 // We should check that there are no special ACES for the group we
176 // are interested, which is nt\authenticated_users.
177 if (base::string16::npos != new_sddl.find(L";AU)"))
179 // Specific ACEs (not inherited) need to go to the front. It is ok if we
180 // are the very first one.
181 size_t pos_insert = new_sddl.find(L"(");
182 if (base::string16::npos == pos_insert)
184 // All good, time to change the dacl.
185 new_sddl.insert(pos_insert, kAllowACE);
186 if (!::ConvertStringSecurityDescriptorToSecurityDescriptorW(new_sddl.c_str(),
187 SDDL_REVISION_1, &sd, NULL))
189 bool rv = ::SetFileSecurityW(exe.value().c_str(), DACL_SECURITY_INFORMATION,
195 // This function launches setup as the currently logged-in interactive
196 // user that is the user whose logon session is attached to winsta0\default.
197 // It assumes that currently we are running as SYSTEM in a non-interactive
199 // The function fails if there is no interactive session active, basically
200 // the computer is on but nobody has logged in locally.
201 // Remote Desktop sessions do not count as interactive sessions; running this
202 // method as a user logged in via remote desktop will do nothing.
203 bool LaunchSetupAsConsoleUser(CommandLine* cmd_line) {
204 // Convey to the invoked setup.exe that it's operating on a system-level
206 cmd_line->AppendSwitch(switches::kSystemLevel);
208 // Propagate --verbose-logging to the invoked setup.exe.
209 if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kVerboseLogging))
210 cmd_line->AppendSwitch(switches::kVerboseLogging);
212 // Get the Google Update results key, and pass it on the command line to
213 // the child process.
214 int key = GoogleUpdateSettings::DuplicateGoogleUpdateSystemClientKey();
215 cmd_line->AppendSwitchASCII(switches::kToastResultsKey,
216 base::IntToString(key));
218 if (base::win::GetVersion() > base::win::VERSION_XP) {
219 // Make sure that in Vista and Above we have the proper DACLs so
220 // the interactive user can launch it.
221 if (!FixDACLsForExecute(cmd_line->GetProgram()))
225 DWORD console_id = ::WTSGetActiveConsoleSessionId();
226 if (console_id == 0xFFFFFFFF) {
227 PLOG(ERROR) << __FUNCTION__ << " failed to get active session id";
231 if (!::WTSQueryUserToken(console_id, &user_token)) {
232 PLOG(ERROR) << __FUNCTION__ << " failed to get user token for console_id "
236 // Note: Handle inheritance must be true in order for the child process to be
237 // able to use the duplicated handle above (Google Update results).
238 base::LaunchOptions options;
239 options.as_user = user_token;
240 options.inherit_handles = true;
241 options.empty_desktop_name = true;
242 VLOG(1) << __FUNCTION__ << " launching " << cmd_line->GetCommandLineString();
243 bool launched = base::LaunchProcess(*cmd_line, options, NULL);
244 ::CloseHandle(user_token);
245 VLOG(1) << __FUNCTION__ << " result: " << launched;
249 // A helper function that writes to HKLM if the handle was passed through the
250 // command line, but HKCU otherwise. |experiment_group| is the value to write
251 // and |last_write| is used when writing to HKLM to determine whether to close
252 // the handle when done.
253 void SetClient(const base::string16& experiment_group, bool last_write) {
254 static int reg_key_handle = -1;
255 if (reg_key_handle == -1) {
256 // If a specific Toast Results key handle (presumably to our HKLM key) was
257 // passed in to the command line (such as for system level installs), we use
258 // it. Otherwise, we write to the key under HKCU.
259 const CommandLine& cmd_line = *CommandLine::ForCurrentProcess();
260 if (cmd_line.HasSwitch(switches::kToastResultsKey)) {
261 // Get the handle to the key under HKLM.
263 cmd_line.GetSwitchValueNative(switches::kToastResultsKey),
270 if (reg_key_handle) {
271 // Use it to write the experiment results.
272 GoogleUpdateSettings::WriteGoogleUpdateSystemClientKey(
273 reg_key_handle, google_update::kRegClientField, experiment_group);
275 CloseHandle((HANDLE) reg_key_handle);
278 GoogleUpdateSettings::SetClient(experiment_group);
284 bool CreateExperimentDetails(int flavor, ExperimentDetails* experiment) {
285 struct FlavorDetails {
289 // Maximum number of experiment flavors we support.
290 static const int kMax = 4;
291 // This struct determines which experiment flavors we show for each locale and
294 // Plugin infobar experiment:
295 // The experiment in 2011 used PIxx codes.
297 // Inactive user toast experiment:
298 // The experiment in Dec 2009 used TGxx and THxx.
299 // The experiment in Feb 2010 used TKxx and TLxx.
300 // The experiment in Apr 2010 used TMxx and TNxx.
301 // The experiment in Oct 2010 used TVxx TWxx TXxx TYxx.
302 // The experiment in Feb 2011 used SJxx SKxx SLxx SMxx.
303 // The experiment in Mar 2012 used ZAxx ZBxx ZCxx.
304 // The experiment in Jan 2013 uses DAxx.
305 using namespace attrition_experiments;
307 static const struct UserExperimentSpecs {
308 const wchar_t* locale; // Locale to show this experiment for (* for all).
309 const wchar_t* brands; // Brand codes show this experiment for (* for all).
310 int control_group; // Size of the control group, in percentages.
311 const wchar_t* prefix; // The two letter experiment code. The second letter
312 // will be incremented with the flavor.
313 FlavorDetails flavors[kMax];
315 // The first match from top to bottom is used so this list should be ordered
316 // most-specific rule first.
317 { L"*", L"GGRV", // All locales, GGRV is enterprise.
318 0, // 0 percent control group.
319 L"EA", // Experiment is EAxx, EBxx, etc.
320 // No flavors means no experiment.
327 { L"*", L"*", // All locales, all brands.
328 5, // 5 percent control group.
329 L"DA", // Experiment is DAxx.
330 // One single flavor.
331 { { IDS_TRY_TOAST_HEADING3, kToastUiMakeDefault },
339 base::string16 locale;
340 GoogleUpdateSettings::GetLanguage(&locale);
341 if (locale.empty() || (locale == base::ASCIIToWide("en")))
342 locale = base::ASCIIToWide("en-US");
344 base::string16 brand;
345 if (!GoogleUpdateSettings::GetBrand(&brand))
346 brand = base::ASCIIToWide(""); // Could still be viable for catch-all rules
348 for (int i = 0; i < arraysize(kExperiments); ++i) {
349 if (kExperiments[i].locale != locale &&
350 kExperiments[i].locale != base::ASCIIToWide("*"))
353 std::vector<base::string16> brand_codes;
354 base::SplitString(kExperiments[i].brands, L',', &brand_codes);
355 if (brand_codes.empty())
357 for (std::vector<base::string16>::iterator it = brand_codes.begin();
358 it != brand_codes.end(); ++it) {
359 if (*it != brand && *it != L"*")
361 // We have found our match.
362 const UserExperimentSpecs& match = kExperiments[i];
363 // Find out how many flavors we have. Zero means no experiment.
365 while (match.flavors[num_flavors].heading_id) { ++num_flavors; }
370 flavor = base::RandInt(0, num_flavors - 1);
371 experiment->flavor = flavor;
372 experiment->heading = match.flavors[flavor].heading_id;
373 experiment->control_group = match.control_group;
374 const wchar_t prefix[] = { match.prefix[0], match.prefix[1] + flavor, 0 };
375 experiment->prefix = prefix;
376 experiment->flags = match.flavors[flavor].flags;
384 // Currently we only have one experiment: the inactive user toast. Which only
385 // applies for users doing upgrades.
387 // There are three scenarios when this function is called:
388 // 1- Is a per-user-install and it updated: perform the experiment
389 // 2- Is a system-install and it updated : relaunch as the interactive user
390 // 3- It has been re-launched from the #2 case. In this case we enter
391 // this function with |system_install| true and a REENTRY_SYS_UPDATE status.
392 void LaunchBrowserUserExperiment(const CommandLine& base_cmd_line,
393 InstallStatus status,
396 if (NEW_VERSION_UPDATED == status) {
397 CommandLine cmd_line(base_cmd_line);
398 cmd_line.AppendSwitch(switches::kSystemLevelToast);
399 // We need to relaunch as the interactive user.
400 LaunchSetupAsConsoleUser(&cmd_line);
404 if (status != NEW_VERSION_UPDATED && status != REENTRY_SYS_UPDATE) {
405 // We are not updating or in re-launch. Exit.
410 // The |flavor| value ends up being processed by TryChromeDialogView to show
411 // different experiments.
412 ExperimentDetails experiment;
413 if (!CreateExperimentDetails(-1, &experiment)) {
414 VLOG(1) << "Failed to get experiment details.";
417 int flavor = experiment.flavor;
418 base::string16 base_group = experiment.prefix;
420 base::string16 brand;
421 if (GoogleUpdateSettings::GetBrand(&brand) && (brand == L"CHXX")) {
422 // Testing only: the user automatically qualifies for the experiment.
423 VLOG(1) << "Experiment qualification bypass";
425 // Check that the user was not already drafted in this experiment.
426 base::string16 client;
427 GoogleUpdateSettings::GetClient(&client);
428 if (client.size() > 2) {
429 if (base_group == client.substr(0, 2)) {
430 VLOG(1) << "User already participated in this experiment";
434 const bool experiment_enabled = false;
435 if (!experiment_enabled) {
436 VLOG(1) << "Toast experiment is disabled.";
440 // Check browser usage inactivity by the age of the last-write time of the
441 // relevant chrome user data directory.
442 const int kThirtyDays = 30 * 24;
443 const int dir_age_hours = GetUserDataDirectoryWriteAgeInHours();
444 if (dir_age_hours < 0) {
445 // This means that we failed to find the user data dir. The most likely
446 // cause is that this user has not ever used chrome at all which can
447 // happen in a system-level install.
448 SetClient(base_group + kToastUDDirFailure, true);
450 } else if (dir_age_hours < kThirtyDays) {
451 // An active user, so it does not qualify.
452 VLOG(1) << "Chrome used in last " << dir_age_hours << " hours";
453 SetClient(base_group + kToastActiveGroup, true);
456 // Check to see if this user belongs to the control group.
457 double control_group = 1.0 * (100 - experiment.control_group) / 100;
458 if (base::RandDouble() > control_group) {
459 SetClient(base_group + kToastExpControlGroup, true);
460 VLOG(1) << "User is control group";
465 VLOG(1) << "User drafted for toast experiment " << flavor;
466 SetClient(base_group + kToastExpBaseGroup, false);
467 // User level: The experiment needs to be performed in a different process
468 // because google_update expects the upgrade process to be quick and nimble.
469 // System level: We have already been relaunched, so we don't need to be
470 // quick, but we relaunch to follow the exact same codepath.
471 CommandLine cmd_line(base_cmd_line);
472 cmd_line.AppendSwitchASCII(switches::kInactiveUserToast,
473 base::IntToString(flavor));
474 cmd_line.AppendSwitchASCII(switches::kExperimentGroup,
475 base::UTF16ToASCII(base_group));
476 LaunchSetup(&cmd_line, system_level);
479 // User qualifies for the experiment. To test, use --try-chrome-again=|flavor|
480 // as a parameter to chrome.exe.
481 void InactiveUserToastExperiment(int flavor,
482 const base::string16& experiment_group,
483 const Product& product,
484 const base::FilePath& application_path) {
485 // Add the 'welcome back' url for chrome to show.
486 CommandLine options(CommandLine::NO_PROGRAM);
487 options.AppendSwitchNative(::switches::kTryChromeAgain,
488 base::IntToString16(flavor));
489 // Prepend the url with a space.
490 base::string16 url(GetWelcomeBackUrl());
491 options.AppendArg("--");
492 options.AppendArgNative(url);
493 // The command line should now have the url added as:
494 // "chrome.exe -- <url>"
495 DCHECK_NE(base::string16::npos,
496 options.GetCommandLineString().find(L" -- " + url));
498 // Launch chrome now. It will show the toast UI.
500 if (!product.LaunchChromeAndWait(application_path, options, &exit_code))
503 // The chrome process has exited, figure out what happened.
504 const wchar_t* outcome = NULL;
506 case content::RESULT_CODE_NORMAL_EXIT:
507 outcome = kToastExpTriesOkGroup;
509 case chrome::RESULT_CODE_NORMAL_EXIT_CANCEL:
510 outcome = kToastExpCancelGroup;
512 case chrome::RESULT_CODE_NORMAL_EXIT_EXP2:
513 outcome = kToastExpUninstallGroup;
516 outcome = kToastExpTriesErrorGroup;
518 // Write to the |client| key for the last time.
519 SetClient(experiment_group + outcome, true);
521 if (outcome != kToastExpUninstallGroup)
523 // The user wants to uninstall. This is a best effort operation. Note that
524 // we waited for chrome to exit so the uninstall would not detect chrome
526 bool system_level_toast = CommandLine::ForCurrentProcess()->HasSwitch(
527 switches::kSystemLevelToast);
529 CommandLine cmd(InstallUtil::GetChromeUninstallCmd(
530 system_level_toast, product.distribution()->GetType()));
531 base::LaunchProcess(cmd, base::LaunchOptions(), NULL);
534 } // namespace installer