• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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.
4 
5 #include "chrome/installer/util/user_experiment.h"
6 
7 #include <windows.h>
8 #include <sddl.h>
9 #include <wtsapi32.h>
10 #include <vector>
11 
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"
34 
35 #pragma comment(lib, "wtsapi32.lib")
36 
37 namespace installer {
38 
39 namespace {
40 
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";
51 
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.
LocalizeUrl(const wchar_t * url)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);
60 }
61 
GetWelcomeBackUrl()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);
66 }
67 
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.
FileTimeToHours(const FILETIME & time)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);
74 }
75 
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.
GetDirectoryWriteTimeInHours(const wchar_t * path)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));
83   if (!file.IsValid())
84     return -1;
85 
86   FILETIME time;
87   return ::GetFileTime(file, NULL, NULL, &time) ? FileTimeToHours(time) : -1;
88 }
89 
90 // Returns the time in hours since the last write to the user data directory.
91 // A return value of 14 means that the directory was last written 14 hours ago.
92 // Returns -1 if there was an error retrieving the directory.
GetUserDataDirectoryWriteAgeInHours()93 int GetUserDataDirectoryWriteAgeInHours() {
94   base::FilePath user_data_dir;
95   if (!PathService::Get(chrome::DIR_USER_DATA, &user_data_dir))
96     return -1;
97   int dir_time = GetDirectoryWriteTimeInHours(user_data_dir.value().c_str());
98   if (dir_time < 0)
99     return dir_time;
100   FILETIME time;
101   GetSystemTimeAsFileTime(&time);
102   int now_time = FileTimeToHours(time);
103   if (dir_time >= now_time)
104     return 0;
105   return (now_time - dir_time);
106 }
107 
108 // Launches setup.exe (located at |setup_path|) with |cmd_line|.
109 // If system_level_toast is true, appends --system-level-toast.
110 // If handle to experiment result key was given at startup, re-add it.
111 // Does not wait for the process to terminate.
112 // |cmd_line| may be modified as a result of this call.
LaunchSetup(CommandLine * cmd_line,bool system_level_toast)113 bool LaunchSetup(CommandLine* cmd_line, bool system_level_toast) {
114   const CommandLine& current_cmd_line = *CommandLine::ForCurrentProcess();
115 
116   // Propagate --verbose-logging to the invoked setup.exe.
117   if (current_cmd_line.HasSwitch(switches::kVerboseLogging))
118     cmd_line->AppendSwitch(switches::kVerboseLogging);
119 
120   // Re-add the system level toast flag.
121   if (system_level_toast) {
122     cmd_line->AppendSwitch(switches::kSystemLevel);
123     cmd_line->AppendSwitch(switches::kSystemLevelToast);
124 
125     // Re-add the toast result key. We need to do this because Setup running as
126     // system passes the key to Setup running as user, but that child process
127     // does not perform the actual toasting, it launches another Setup (as user)
128     // to do so. That is the process that needs the key.
129     std::string key(switches::kToastResultsKey);
130     std::string toast_key = current_cmd_line.GetSwitchValueASCII(key);
131     if (!toast_key.empty()) {
132       cmd_line->AppendSwitchASCII(key, toast_key);
133 
134       // Use handle inheritance to make sure the duplicated toast results key
135       // gets inherited by the child process.
136       base::LaunchOptions options;
137       options.inherit_handles = true;
138       return base::LaunchProcess(*cmd_line, options, NULL);
139     }
140   }
141 
142   return base::LaunchProcess(*cmd_line, base::LaunchOptions(), NULL);
143 }
144 
145 // For System level installs, setup.exe lives in the system temp, which
146 // is normally c:\windows\temp. In many cases files inside this folder
147 // are not accessible for execution by regular user accounts.
148 // This function changes the permissions so that any authenticated user
149 // can launch |exe| later on. This function should only be called if the
150 // code is running at the system level.
FixDACLsForExecute(const base::FilePath & exe)151 bool FixDACLsForExecute(const base::FilePath& exe) {
152   // The general strategy to is to add an ACE to the exe DACL the quick
153   // and dirty way: a) read the DACL b) convert it to sddl string c) add the
154   // new ACE to the string d) convert sddl string back to DACL and finally
155   // e) write new dacl.
156   char buff[1024];
157   DWORD len = sizeof(buff);
158   PSECURITY_DESCRIPTOR sd = reinterpret_cast<PSECURITY_DESCRIPTOR>(buff);
159   if (!::GetFileSecurityW(exe.value().c_str(), DACL_SECURITY_INFORMATION,
160                           sd, len, &len)) {
161     return false;
162   }
163   wchar_t* sddl = 0;
164   if (!::ConvertSecurityDescriptorToStringSecurityDescriptorW(sd,
165       SDDL_REVISION_1, DACL_SECURITY_INFORMATION, &sddl, NULL))
166     return false;
167   base::string16 new_sddl(sddl);
168   ::LocalFree(sddl);
169   sd = NULL;
170   // See MSDN for the  security descriptor definition language (SDDL) syntax,
171   // in our case we add "A;" generic read 'GR' and generic execute 'GX' for
172   // the nt\authenticated_users 'AU' group, that becomes:
173   const wchar_t kAllowACE[] = L"(A;;GRGX;;;AU)";
174   // We should check that there are no special ACES for the group we
175   // are interested, which is nt\authenticated_users.
176   if (base::string16::npos != new_sddl.find(L";AU)"))
177     return false;
178   // Specific ACEs (not inherited) need to go to the front. It is ok if we
179   // are the very first one.
180   size_t pos_insert = new_sddl.find(L"(");
181   if (base::string16::npos == pos_insert)
182     return false;
183   // All good, time to change the dacl.
184   new_sddl.insert(pos_insert, kAllowACE);
185   if (!::ConvertStringSecurityDescriptorToSecurityDescriptorW(new_sddl.c_str(),
186       SDDL_REVISION_1, &sd, NULL))
187     return false;
188   bool rv = ::SetFileSecurityW(exe.value().c_str(), DACL_SECURITY_INFORMATION,
189                                sd) == TRUE;
190   ::LocalFree(sd);
191   return rv;
192 }
193 
194 // This function launches setup as the currently logged-in interactive
195 // user that is the user whose logon session is attached to winsta0\default.
196 // It assumes that currently we are running as SYSTEM in a non-interactive
197 // windowstation.
198 // The function fails if there is no interactive session active, basically
199 // the computer is on but nobody has logged in locally.
200 // Remote Desktop sessions do not count as interactive sessions; running this
201 // method as a user logged in via remote desktop will do nothing.
LaunchSetupAsConsoleUser(CommandLine * cmd_line)202 bool LaunchSetupAsConsoleUser(CommandLine* cmd_line) {
203   // Convey to the invoked setup.exe that it's operating on a system-level
204   // installation.
205   cmd_line->AppendSwitch(switches::kSystemLevel);
206 
207   // Propagate --verbose-logging to the invoked setup.exe.
208   if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kVerboseLogging))
209     cmd_line->AppendSwitch(switches::kVerboseLogging);
210 
211   // Get the Google Update results key, and pass it on the command line to
212   // the child process.
213   int key = GoogleUpdateSettings::DuplicateGoogleUpdateSystemClientKey();
214   cmd_line->AppendSwitchASCII(switches::kToastResultsKey,
215                               base::IntToString(key));
216 
217   if (base::win::GetVersion() > base::win::VERSION_XP) {
218     // Make sure that in Vista and Above we have the proper DACLs so
219     // the interactive user can launch it.
220     if (!FixDACLsForExecute(cmd_line->GetProgram()))
221       NOTREACHED();
222   }
223 
224   DWORD console_id = ::WTSGetActiveConsoleSessionId();
225   if (console_id == 0xFFFFFFFF) {
226     PLOG(ERROR) << __FUNCTION__ << " failed to get active session id";
227     return false;
228   }
229   HANDLE user_token;
230   if (!::WTSQueryUserToken(console_id, &user_token)) {
231     PLOG(ERROR) << __FUNCTION__ << " failed to get user token for console_id "
232                 << console_id;
233     return false;
234   }
235   // Note: Handle inheritance must be true in order for the child process to be
236   // able to use the duplicated handle above (Google Update results).
237   base::LaunchOptions options;
238   options.as_user = user_token;
239   options.inherit_handles = true;
240   options.empty_desktop_name = true;
241   VLOG(1) << __FUNCTION__ << " launching " << cmd_line->GetCommandLineString();
242   bool launched = base::LaunchProcess(*cmd_line, options, NULL);
243   ::CloseHandle(user_token);
244   VLOG(1) << __FUNCTION__ << "   result: " << launched;
245   return launched;
246 }
247 
248 // A helper function that writes to HKLM if the handle was passed through the
249 // command line, but HKCU otherwise. |experiment_group| is the value to write
250 // and |last_write| is used when writing to HKLM to determine whether to close
251 // the handle when done.
SetClient(const base::string16 & experiment_group,bool last_write)252 void SetClient(const base::string16& experiment_group, bool last_write) {
253   static int reg_key_handle = -1;
254   if (reg_key_handle == -1) {
255     // If a specific Toast Results key handle (presumably to our HKLM key) was
256     // passed in to the command line (such as for system level installs), we use
257     // it. Otherwise, we write to the key under HKCU.
258     const CommandLine& cmd_line = *CommandLine::ForCurrentProcess();
259     if (cmd_line.HasSwitch(switches::kToastResultsKey)) {
260       // Get the handle to the key under HKLM.
261       base::StringToInt(
262           cmd_line.GetSwitchValueNative(switches::kToastResultsKey),
263           &reg_key_handle);
264     } else {
265       reg_key_handle = 0;
266     }
267   }
268 
269   if (reg_key_handle) {
270     // Use it to write the experiment results.
271     GoogleUpdateSettings::WriteGoogleUpdateSystemClientKey(
272         reg_key_handle, google_update::kRegClientField, experiment_group);
273     if (last_write)
274       CloseHandle((HANDLE) reg_key_handle);
275   } else {
276     // Write to HKCU.
277     GoogleUpdateSettings::SetClient(experiment_group);
278   }
279 }
280 
281 }  // namespace
282 
CreateExperimentDetails(int flavor,ExperimentDetails * experiment)283 bool CreateExperimentDetails(int flavor, ExperimentDetails* experiment) {
284   struct FlavorDetails {
285     int heading_id;
286     int flags;
287   };
288   // Maximum number of experiment flavors we support.
289   static const int kMax = 4;
290   // This struct determines which experiment flavors we show for each locale and
291   // brand.
292   //
293   // Plugin infobar experiment:
294   // The experiment in 2011 used PIxx codes.
295   //
296   // Inactive user toast experiment:
297   // The experiment in Dec 2009 used TGxx and THxx.
298   // The experiment in Feb 2010 used TKxx and TLxx.
299   // The experiment in Apr 2010 used TMxx and TNxx.
300   // The experiment in Oct 2010 used TVxx TWxx TXxx TYxx.
301   // The experiment in Feb 2011 used SJxx SKxx SLxx SMxx.
302   // The experiment in Mar 2012 used ZAxx ZBxx ZCxx.
303   // The experiment in Jan 2013 uses DAxx.
304   using namespace attrition_experiments;
305 
306   static const struct UserExperimentSpecs {
307     const wchar_t* locale;  // Locale to show this experiment for (* for all).
308     const wchar_t* brands;  // Brand codes show this experiment for (* for all).
309     int control_group;      // Size of the control group, in percentages.
310     const wchar_t* prefix;  // The two letter experiment code. The second letter
311                             // will be incremented with the flavor.
312     FlavorDetails flavors[kMax];
313   } kExperiments[] = {
314     // The first match from top to bottom is used so this list should be ordered
315     // most-specific rule first.
316     { L"*", L"GGRV",  // All locales, GGRV is enterprise.
317       0,              // 0 percent control group.
318       L"EA",          // Experiment is EAxx, EBxx, etc.
319       // No flavors means no experiment.
320       { { 0, 0 },
321         { 0, 0 },
322         { 0, 0 },
323         { 0, 0 }
324       }
325     },
326     { L"*", L"*",     // All locales, all brands.
327       5,              // 5 percent control group.
328       L"DA",          // Experiment is DAxx.
329       // One single flavor.
330       { { IDS_TRY_TOAST_HEADING3, kToastUiMakeDefault },
331         { 0, 0 },
332         { 0, 0 },
333         { 0, 0 }
334       }
335     }
336   };
337 
338   base::string16 locale;
339   GoogleUpdateSettings::GetLanguage(&locale);
340   if (locale.empty() || (locale == base::ASCIIToWide("en")))
341     locale = base::ASCIIToWide("en-US");
342 
343   base::string16 brand;
344   if (!GoogleUpdateSettings::GetBrand(&brand))
345     brand = base::ASCIIToWide("");  // Could still be viable for catch-all rules
346 
347   for (int i = 0; i < arraysize(kExperiments); ++i) {
348     if (kExperiments[i].locale != locale &&
349         kExperiments[i].locale != base::ASCIIToWide("*"))
350       continue;
351 
352     std::vector<base::string16> brand_codes;
353     base::SplitString(kExperiments[i].brands, L',', &brand_codes);
354     if (brand_codes.empty())
355       return false;
356     for (std::vector<base::string16>::iterator it = brand_codes.begin();
357          it != brand_codes.end(); ++it) {
358       if (*it != brand && *it != L"*")
359         continue;
360       // We have found our match.
361       const UserExperimentSpecs& match = kExperiments[i];
362       // Find out how many flavors we have. Zero means no experiment.
363       int num_flavors = 0;
364       while (match.flavors[num_flavors].heading_id) { ++num_flavors; }
365       if (!num_flavors)
366         return false;
367 
368       if (flavor < 0)
369         flavor = base::RandInt(0, num_flavors - 1);
370       experiment->flavor = flavor;
371       experiment->heading = match.flavors[flavor].heading_id;
372       experiment->control_group = match.control_group;
373       const wchar_t prefix[] = { match.prefix[0], match.prefix[1] + flavor, 0 };
374       experiment->prefix = prefix;
375       experiment->flags = match.flavors[flavor].flags;
376       return true;
377     }
378   }
379 
380   return false;
381 }
382 
383 // Currently we only have one experiment: the inactive user toast. Which only
384 // applies for users doing upgrades.
385 
386 // There are three scenarios when this function is called:
387 // 1- Is a per-user-install and it updated: perform the experiment
388 // 2- Is a system-install and it updated : relaunch as the interactive user
389 // 3- It has been re-launched from the #2 case. In this case we enter
390 //    this function with |system_install| true and a REENTRY_SYS_UPDATE status.
LaunchBrowserUserExperiment(const CommandLine & base_cmd_line,InstallStatus status,bool system_level)391 void LaunchBrowserUserExperiment(const CommandLine& base_cmd_line,
392                                  InstallStatus status,
393                                  bool system_level) {
394   if (system_level) {
395     if (NEW_VERSION_UPDATED == status) {
396       CommandLine cmd_line(base_cmd_line);
397       cmd_line.AppendSwitch(switches::kSystemLevelToast);
398       // We need to relaunch as the interactive user.
399       LaunchSetupAsConsoleUser(&cmd_line);
400       return;
401     }
402   } else {
403     if (status != NEW_VERSION_UPDATED && status != REENTRY_SYS_UPDATE) {
404       // We are not updating or in re-launch. Exit.
405       return;
406     }
407   }
408 
409   // The |flavor| value ends up being processed by TryChromeDialogView to show
410   // different experiments.
411   ExperimentDetails experiment;
412   if (!CreateExperimentDetails(-1, &experiment)) {
413     VLOG(1) << "Failed to get experiment details.";
414     return;
415   }
416   int flavor = experiment.flavor;
417   base::string16 base_group = experiment.prefix;
418 
419   base::string16 brand;
420   if (GoogleUpdateSettings::GetBrand(&brand) && (brand == L"CHXX")) {
421     // Testing only: the user automatically qualifies for the experiment.
422     VLOG(1) << "Experiment qualification bypass";
423   } else {
424     // Check that the user was not already drafted in this experiment.
425     base::string16 client;
426     GoogleUpdateSettings::GetClient(&client);
427     if (client.size() > 2) {
428       if (base_group == client.substr(0, 2)) {
429         VLOG(1) << "User already participated in this experiment";
430         return;
431       }
432     }
433     const bool experiment_enabled = false;
434     if (!experiment_enabled) {
435       VLOG(1) << "Toast experiment is disabled.";
436       return;
437     }
438 
439     // Check browser usage inactivity by the age of the last-write time of the
440     // relevant chrome user data directory.
441     const int kThirtyDays = 30 * 24;
442     const int dir_age_hours = GetUserDataDirectoryWriteAgeInHours();
443     if (dir_age_hours < 0) {
444       // This means that we failed to find the user data dir. The most likely
445       // cause is that this user has not ever used chrome at all which can
446       // happen in a system-level install.
447       SetClient(base_group + kToastUDDirFailure, true);
448       return;
449     } else if (dir_age_hours < kThirtyDays) {
450       // An active user, so it does not qualify.
451       VLOG(1) << "Chrome used in last " << dir_age_hours << " hours";
452       SetClient(base_group + kToastActiveGroup, true);
453       return;
454     }
455     // Check to see if this user belongs to the control group.
456     double control_group = 1.0 * (100 - experiment.control_group) / 100;
457     if (base::RandDouble() > control_group) {
458       SetClient(base_group + kToastExpControlGroup, true);
459       VLOG(1) << "User is control group";
460       return;
461     }
462   }
463 
464   VLOG(1) << "User drafted for toast experiment " << flavor;
465   SetClient(base_group + kToastExpBaseGroup, false);
466   // User level: The experiment needs to be performed in a different process
467   // because google_update expects the upgrade process to be quick and nimble.
468   // System level: We have already been relaunched, so we don't need to be
469   // quick, but we relaunch to follow the exact same codepath.
470   CommandLine cmd_line(base_cmd_line);
471   cmd_line.AppendSwitchASCII(switches::kInactiveUserToast,
472                              base::IntToString(flavor));
473   cmd_line.AppendSwitchASCII(switches::kExperimentGroup,
474                              base::UTF16ToASCII(base_group));
475   LaunchSetup(&cmd_line, system_level);
476 }
477 
478 // User qualifies for the experiment. To test, use --try-chrome-again=|flavor|
479 // as a parameter to chrome.exe.
InactiveUserToastExperiment(int flavor,const base::string16 & experiment_group,const Product & product,const base::FilePath & application_path)480 void InactiveUserToastExperiment(int flavor,
481                                  const base::string16& experiment_group,
482                                  const Product& product,
483                                  const base::FilePath& application_path) {
484   // Add the 'welcome back' url for chrome to show.
485   CommandLine options(CommandLine::NO_PROGRAM);
486   options.AppendSwitchNative(::switches::kTryChromeAgain,
487       base::IntToString16(flavor));
488   // Prepend the url with a space.
489   base::string16 url(GetWelcomeBackUrl());
490   options.AppendArg("--");
491   options.AppendArgNative(url);
492   // The command line should now have the url added as:
493   // "chrome.exe -- <url>"
494   DCHECK_NE(base::string16::npos,
495             options.GetCommandLineString().find(L" -- " + url));
496 
497   // Launch chrome now. It will show the toast UI.
498   int32 exit_code = 0;
499   if (!product.LaunchChromeAndWait(application_path, options, &exit_code))
500     return;
501 
502   // The chrome process has exited, figure out what happened.
503   const wchar_t* outcome = NULL;
504   switch (exit_code) {
505     case content::RESULT_CODE_NORMAL_EXIT:
506       outcome = kToastExpTriesOkGroup;
507       break;
508     case chrome::RESULT_CODE_NORMAL_EXIT_CANCEL:
509       outcome = kToastExpCancelGroup;
510       break;
511     case chrome::RESULT_CODE_NORMAL_EXIT_EXP2:
512       outcome = kToastExpUninstallGroup;
513       break;
514     default:
515       outcome = kToastExpTriesErrorGroup;
516   };
517   // Write to the |client| key for the last time.
518   SetClient(experiment_group + outcome, true);
519 
520   if (outcome != kToastExpUninstallGroup)
521     return;
522   // The user wants to uninstall. This is a best effort operation. Note that
523   // we waited for chrome to exit so the uninstall would not detect chrome
524   // running.
525   bool system_level_toast = CommandLine::ForCurrentProcess()->HasSwitch(
526       switches::kSystemLevelToast);
527 
528   CommandLine cmd(InstallUtil::GetChromeUninstallCmd(
529                       system_level_toast, product.distribution()->GetType()));
530   base::LaunchProcess(cmd, base::LaunchOptions(), NULL);
531 }
532 
533 }  // namespace installer
534