#include "chrome/browser/first_run/first_run.h"
#include <shellapi.h>
#include <shlobj.h>
#include <windows.h>
#include "base/environment.h"
#include "base/file_util.h"
#include "base/path_service.h"
#include "base/process_util.h"
#include "base/string_number_conversions.h"
#include "base/string_split.h"
#include "base/stringprintf.h"
#include "base/utf_string_conversions.h"
#include "base/win/metro.h"
#include "base/win/object_watcher.h"
#include "base/win/windows_version.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/extensions/updater/extension_updater.h"
#include "chrome/browser/first_run/first_run_import_observer.h"
#include "chrome/browser/first_run/first_run_internal.h"
#include "chrome/browser/importer/importer_host.h"
#include "chrome/browser/importer/importer_list.h"
#include "chrome/browser/importer/importer_progress_dialog.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/process_singleton.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/shell_integration.h"
#include "chrome/common/chrome_notification_types.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_result_codes.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/worker_thread_ticker.h"
#include "chrome/installer/util/browser_distribution.h"
#include "chrome/installer/util/google_update_settings.h"
#include "chrome/installer/util/install_util.h"
#include "chrome/installer/util/master_preferences.h"
#include "chrome/installer/util/master_preferences_constants.h"
#include "chrome/installer/util/shell_util.h"
#include "chrome/installer/util/util_constants.h"
#include "content/public/browser/notification_service.h"
#include "content/public/browser/user_metrics.h"
#include "google_update/google_update_idl.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "grit/locale_settings.h"
#include "grit/theme_resources.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/layout.h"
#include "ui/base/ui_base_switches.h"
#include "ui/base/win/shell.h"
namespace {
class FirstRunDelayedTasks : public content::NotificationObserver {
public:
enum Tasks {
NO_TASK,
INSTALL_EXTENSIONS
};
explicit FirstRunDelayedTasks(Tasks task) {
if (task == INSTALL_EXTENSIONS) {
registrar_.Add(this, chrome::NOTIFICATION_EXTENSIONS_READY,
content::NotificationService::AllSources());
}
registrar_.Add(this, chrome::NOTIFICATION_BROWSER_CLOSED,
content::NotificationService::AllSources());
}
virtual void Observe(int type,
const content::NotificationSource& source,
const content::NotificationDetails& details) OVERRIDE {
if (type == chrome::NOTIFICATION_EXTENSIONS_READY) {
DoExtensionWork(
content::Source<Profile>(source).ptr()->GetExtensionService());
}
delete this;
}
private:
~FirstRunDelayedTasks() {}
void DoExtensionWork(ExtensionService* service) {
if (service)
service->updater()->CheckNow();
}
content::NotificationRegistrar registrar_;
};
bool CreateChromeDesktopShortcut() {
FilePath chrome_exe;
if (!PathService::Get(base::FILE_EXE, &chrome_exe))
return false;
BrowserDistribution* dist = BrowserDistribution::GetDistribution();
if (!dist || !dist->CanCreateDesktopShortcuts())
return false;
return ShellUtil::CreateChromeDesktopShortcut(
dist,
chrome_exe.value(),
dist->GetAppDescription(),
L"",
L"",
chrome_exe.value(),
dist->GetIconIndex(),
ShellUtil::CURRENT_USER,
ShellUtil::SHORTCUT_CREATE_ALWAYS);
}
bool CreateChromeQuickLaunchShortcut() {
FilePath chrome_exe;
if (!PathService::Get(base::FILE_EXE, &chrome_exe))
return false;
BrowserDistribution* dist = BrowserDistribution::GetDistribution();
return ShellUtil::CreateChromeQuickLaunchShortcut(
dist,
chrome_exe.value(),
ShellUtil::CURRENT_USER,
ShellUtil::SHORTCUT_CREATE_ALWAYS);
}
void PlatformSetup(Profile* profile) {
CreateChromeDesktopShortcut();
if (base::win::GetVersion() < base::win::VERSION_WIN7)
CreateChromeQuickLaunchShortcut();
}
bool LaunchSetupForEula(const FilePath::StringType& value, int* ret_code) {
FilePath exe_dir;
if (!PathService::Get(base::DIR_MODULE, &exe_dir))
return false;
exe_dir = exe_dir.Append(installer::kInstallerDir);
FilePath exe_path = exe_dir.Append(installer::kSetupExe);
base::ProcessHandle ph;
CommandLine cl(CommandLine::NO_PROGRAM);
cl.AppendSwitchNative(installer::switches::kShowEula, value);
CommandLine* browser_command_line = CommandLine::ForCurrentProcess();
if (browser_command_line->HasSwitch(switches::kChromeFrame)) {
cl.AppendSwitch(switches::kChromeFrame);
}
if (base::win::IsMetroProcess()) {
cl.AppendSwitch(installer::switches::kShowEulaForMetro);
ui::win::OpenAnyViaShell(exe_path.value(),
exe_dir.value(),
cl.GetCommandLineString(),
SEE_MASK_FLAG_LOG_USAGE | SEE_MASK_FLAG_NO_UI);
return false;
} else {
base::LaunchOptions launch_options;
launch_options.wait = true;
CommandLine setup_path(exe_path);
setup_path.AppendArguments(cl, false);
DWORD exit_code = 0;
if (!base::LaunchProcess(setup_path, launch_options, &ph) ||
!::GetExitCodeProcess(ph, &exit_code)) {
return false;
}
*ret_code = exit_code;
return true;
}
}
bool GetEULASentinelFilePath(FilePath* path) {
return InstallUtil::GetSentinelFilePath(
installer::kEULASentinelFile,
BrowserDistribution::GetDistribution(),
path);
}
bool IsEULANotAccepted(installer::MasterPreferences* install_prefs) {
bool value = false;
if (install_prefs->GetBool(installer::master_preferences::kRequireEula,
&value) && value) {
FilePath eula_sentinel;
if (!GetEULASentinelFilePath(&eula_sentinel) ||
!file_util::PathExists(eula_sentinel)) {
return true;
}
}
return false;
}
bool WriteEULAtoTempFile(FilePath* eula_path) {
std::string terms = l10n_util::GetStringUTF8(IDS_TERMS_HTML);
if (terms.empty())
return false;
FILE *file = file_util::CreateAndOpenTemporaryFile(eula_path);
if (!file)
return false;
bool good = fwrite(terms.data(), terms.size(), 1, file) == 1;
fclose(file);
return good;
}
bool CreateEULASentinel() {
FilePath eula_sentinel;
if (!GetEULASentinelFilePath(&eula_sentinel))
return false;
return file_util::WriteFile(eula_sentinel, "", 0) != -1;
}
bool ShowPostInstallEULAIfNeeded(installer::MasterPreferences* install_prefs) {
if (IsEULANotAccepted(install_prefs)) {
FilePath inner_html;
if (WriteEULAtoTempFile(&inner_html)) {
int retcode = 0;
if (!LaunchSetupForEula(inner_html.value(), &retcode) ||
(retcode != installer::EULA_ACCEPTED &&
retcode != installer::EULA_ACCEPTED_OPT_IN)) {
LOG(WARNING) << "EULA flow requires fast exit.";
return false;
}
CreateEULASentinel();
if (retcode == installer::EULA_ACCEPTED) {
VLOG(1) << "EULA : no collection";
GoogleUpdateSettings::SetCollectStatsConsent(false);
} else if (retcode == installer::EULA_ACCEPTED_OPT_IN) {
VLOG(1) << "EULA : collection consent";
GoogleUpdateSettings::SetCollectStatsConsent(true);
}
}
}
return true;
}
void DoDelayedInstallExtensions() {
new FirstRunDelayedTasks(FirstRunDelayedTasks::INSTALL_EXTENSIONS);
}
void DoDelayedInstallExtensionsIfNeeded(
installer::MasterPreferences* install_prefs) {
DictionaryValue* extensions = 0;
if (install_prefs->GetExtensionsBlock(&extensions)) {
VLOG(1) << "Extensions block found in master preferences";
DoDelayedInstallExtensions();
}
}
class ImportProcessRunner : public base::win::ObjectWatcher::Delegate {
public:
explicit ImportProcessRunner(base::ProcessHandle import_process)
: import_process_(import_process),
exit_code_(content::RESULT_CODE_NORMAL_EXIT) {
watcher_.StartWatching(import_process, this);
MessageLoop::current()->Run();
}
virtual ~ImportProcessRunner() {
::CloseHandle(import_process_);
}
int exit_code() const { return exit_code_; }
virtual void OnObjectSignaled(HANDLE object) OVERRIDE {
DCHECK(object == import_process_);
if (!::GetExitCodeProcess(import_process_, &exit_code_)) {
NOTREACHED();
}
MessageLoop::current()->Quit();
}
private:
base::win::ObjectWatcher watcher_;
base::ProcessHandle import_process_;
DWORD exit_code_;
};
const int kPollHangFrequency = 3000;
class HungImporterMonitor : public WorkerThreadTicker::Callback {
public:
HungImporterMonitor(HWND owner_window, base::ProcessHandle import_process)
: owner_window_(owner_window),
import_process_(import_process),
ticker_(kPollHangFrequency) {
ticker_.RegisterTickHandler(this);
ticker_.Start();
}
virtual ~HungImporterMonitor() {
ticker_.Stop();
ticker_.UnregisterTickHandler(this);
}
private:
virtual void OnTick() OVERRIDE {
if (!import_process_)
return;
HWND active_window = ::GetLastActivePopup(owner_window_);
if (::IsHungAppWindow(active_window) || ::IsHungAppWindow(owner_window_)) {
::TerminateProcess(import_process_, chrome::RESULT_CODE_IMPORTER_HUNG);
import_process_ = NULL;
}
}
HWND owner_window_;
base::ProcessHandle import_process_;
WorkerThreadTicker ticker_;
DISALLOW_COPY_AND_ASSIGN(HungImporterMonitor);
};
std::string EncodeImportParams(int importer_type,
int options,
bool skip_first_run_ui) {
return base::StringPrintf("%d@%d@%d", importer_type, options,
skip_first_run_ui ? 1 : 0);
}
bool DecodeImportParams(const std::string& encoded,
int* importer_type,
int* options,
bool* skip_first_run_ui) {
std::vector<std::string> parts;
base::SplitString(encoded, '@', &parts);
int skip_first_run_ui_int;
if ((parts.size() != 3) || !base::StringToInt(parts[0], importer_type) ||
!base::StringToInt(parts[1], options) ||
!base::StringToInt(parts[2], &skip_first_run_ui_int))
return false;
*skip_first_run_ui = !!skip_first_run_ui_int;
return true;
}
#if !defined(USE_AURA)
int ImportFromBrowser(Profile* profile,
const CommandLine& cmdline) {
std::string import_info = cmdline.GetSwitchValueASCII(switches::kImport);
if (import_info.empty()) {
NOTREACHED();
return false;
}
int importer_type = 0;
int items_to_import = 0;
bool skip_first_run_ui = false;
if (!DecodeImportParams(import_info, &importer_type, &items_to_import,
&skip_first_run_ui)) {
NOTREACHED();
return false;
}
scoped_refptr<ImporterHost> importer_host(new ImporterHost);
FirstRunImportObserver importer_observer;
scoped_refptr<ImporterList> importer_list(new ImporterList(NULL));
importer_list->DetectSourceProfilesHack();
if (skip_first_run_ui)
importer_host->set_headless();
importer::ShowImportProgressDialog(static_cast<uint16>(items_to_import),
importer_host, &importer_observer,
importer_list->GetSourceProfileForImporterType(importer_type), profile,
true);
importer_observer.RunLoop();
return importer_observer.import_result();
}
#endif
bool ImportSettingsWin(Profile* profile,
int importer_type,
int items_to_import,
const FilePath& import_bookmarks_path,
bool skip_first_run_ui) {
if (!items_to_import && import_bookmarks_path.empty()) {
return true;
}
const CommandLine& cmdline = *CommandLine::ForCurrentProcess();
CommandLine import_cmd(cmdline.GetProgram());
const char* kSwitchNames[] = {
switches::kUserDataDir,
switches::kChromeFrame,
switches::kCountry,
};
import_cmd.CopySwitchesFrom(cmdline, kSwitchNames, arraysize(kSwitchNames));
import_cmd.AppendSwitchASCII(switches::kLang,
g_browser_process->GetApplicationLocale());
if (items_to_import) {
import_cmd.AppendSwitchASCII(switches::kImport,
EncodeImportParams(importer_type, items_to_import, skip_first_run_ui));
}
if (!import_bookmarks_path.empty()) {
import_cmd.AppendSwitchPath(switches::kImportFromFile,
import_bookmarks_path);
}
import_cmd.CommandLine::AppendSwitch(switches::kDisableBackgroundNetworking);
base::ProcessHandle import_process;
if (!base::LaunchProcess(import_cmd, base::LaunchOptions(), &import_process))
return false;
ImportProcessRunner import_runner(import_process);
if (profile)
profile->GetPrefs()->ReloadPersistentPrefs();
return (import_runner.exit_code() == content::RESULT_CODE_NORMAL_EXIT);
}
}
namespace first_run {
namespace internal {
bool ImportSettings(Profile* profile,
scoped_refptr<ImporterHost> importer_host,
scoped_refptr<ImporterList> importer_list,
int items_to_import) {
return ImportSettingsWin(
profile,
importer_list->GetSourceProfileAt(0).importer_type,
items_to_import,
FilePath(),
false);
}
bool GetFirstRunSentinelFilePath(FilePath* path) {
return InstallUtil::GetSentinelFilePath(
kSentinelFile,
BrowserDistribution::GetDistribution(),
path);
}
void SetImportPreferencesAndLaunchImport(
MasterPrefs* out_prefs,
installer::MasterPreferences* install_prefs) {
std::string import_bookmarks_path;
install_prefs->GetString(
installer::master_preferences::kDistroImportBookmarksFromFilePref,
&import_bookmarks_path);
if (!IsOrganicFirstRun()) {
if (!(out_prefs->do_import_items & importer::SEARCH_ENGINES)) {
out_prefs->dont_import_items |= importer::SEARCH_ENGINES;
}
if (!(out_prefs->do_import_items & importer::HOME_PAGE)) {
out_prefs->dont_import_items |= importer::HOME_PAGE;
}
if (!(out_prefs->dont_import_items & importer::HISTORY)) {
out_prefs->do_import_items |= importer::HISTORY;
}
}
if (out_prefs->do_import_items || !import_bookmarks_path.empty()) {
scoped_refptr<ImporterList> importer_list(new ImporterList(NULL));
importer_list->DetectSourceProfilesHack();
if (!ImportSettingsWin(NULL,
importer_list->GetSourceProfileAt(0).importer_type,
out_prefs->do_import_items,
FilePath::FromWStringHack(UTF8ToWide(import_bookmarks_path)), true)) {
LOG(WARNING) << "silent import failed";
}
}
}
}
}
namespace first_run {
void AutoImport(
Profile* profile,
bool homepage_defined,
int import_items,
int dont_import_items,
bool make_chrome_default,
ProcessSingleton* process_singleton) {
#if !defined(USE_AURA)
process_singleton->Lock(NULL);
PlatformSetup(profile);
scoped_refptr<ImporterHost> importer_host;
importer_host = new ImporterHost;
internal::AutoImportPlatformCommon(importer_host, profile, homepage_defined,
import_items, dont_import_items,
make_chrome_default);
process_singleton->Unlock();
CreateSentinel();
#endif
}
int ImportNow(Profile* profile, const CommandLine& cmdline) {
int return_code = internal::ImportBookmarkFromFileIfNeeded(profile, cmdline);
#if !defined(USE_AURA)
if (cmdline.HasSwitch(switches::kImport)) {
return_code = ImportFromBrowser(profile, cmdline);
}
#endif
return return_code;
}
FilePath MasterPrefsPath() {
FilePath master_prefs;
if (!PathService::Get(base::DIR_EXE, &master_prefs))
return FilePath();
return master_prefs.AppendASCII(installer::kDefaultMasterPrefs);
}
ProcessMasterPreferencesResult ProcessMasterPreferences(
const FilePath& user_data_dir,
MasterPrefs* out_prefs) {
DCHECK(!user_data_dir.empty());
FilePath master_prefs_path;
scoped_ptr<installer::MasterPreferences>
install_prefs(internal::LoadMasterPrefs(&master_prefs_path));
if (!install_prefs.get())
return SHOW_FIRST_RUN;
out_prefs->new_tabs = install_prefs->GetFirstRunTabs();
internal::SetRLZPref(out_prefs, install_prefs.get());
if (!ShowPostInstallEULAIfNeeded(install_prefs.get()))
return EULA_EXIT_NOW;
if (!internal::CopyPrefFile(user_data_dir, master_prefs_path))
return SHOW_FIRST_RUN;
DoDelayedInstallExtensionsIfNeeded(install_prefs.get());
internal::SetupMasterPrefsFromInstallPrefs(out_prefs,
install_prefs.get());
if (!internal::SkipFirstRunUI(install_prefs.get()))
return SHOW_FIRST_RUN;
if (!CreateSentinel())
return SKIP_FIRST_RUN;
internal::SetShowWelcomePagePrefIfNeeded(install_prefs.get());
internal::SetImportPreferencesAndLaunchImport(out_prefs, install_prefs.get());
internal::SetDefaultBrowser(install_prefs.get());
return SKIP_FIRST_RUN;
}
}