1// Copyright (c) 2011 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/browser/browser_main.h"
6#include "chrome/browser/browser_main_win.h"
7
8#include <shellapi.h>
9#include <windows.h>
10
11#include <algorithm>
12
13#include "base/command_line.h"
14#include "base/environment.h"
15#include "base/i18n/rtl.h"
16#include "base/memory/scoped_native_library.h"
17#include "base/memory/scoped_ptr.h"
18#include "base/path_service.h"
19#include "base/time.h"
20#include "base/utf_string_conversions.h"
21#include "base/win/windows_version.h"
22#include "base/win/wrapped_window_proc.h"
23#include "crypto/nss_util.h"
24#include "chrome/browser/browser_util_win.h"
25#include "chrome/browser/first_run/first_run.h"
26#include "chrome/browser/metrics/metrics_service.h"
27#include "chrome/browser/ui/browser_list.h"
28#include "chrome/browser/ui/views/uninstall_view.h"
29#include "chrome/common/chrome_constants.h"
30#include "chrome/common/chrome_switches.h"
31#include "chrome/common/env_vars.h"
32#include "chrome/installer/util/browser_distribution.h"
33#include "chrome/installer/util/google_update_settings.h"
34#include "chrome/installer/util/helper.h"
35#include "chrome/installer/util/install_util.h"
36#include "chrome/installer/util/shell_util.h"
37#include "content/common/main_function_params.h"
38#include "content/common/result_codes.h"
39#include "grit/chromium_strings.h"
40#include "grit/generated_resources.h"
41#include "net/base/winsock_init.h"
42#include "net/socket/client_socket_factory.h"
43#include "ui/base/l10n/l10n_util.h"
44#include "ui/base/l10n/l10n_util_win.h"
45#include "ui/base/message_box_win.h"
46#include "views/focus/accelerator_handler.h"
47#include "views/window/window.h"
48
49namespace {
50
51typedef HRESULT (STDAPICALLTYPE* RegisterApplicationRestartProc)(
52    const wchar_t* command_line,
53    DWORD flags);
54
55void InitializeWindowProcExceptions() {
56  // Get the breakpad pointer from chrome.exe
57  base::win::WinProcExceptionFilter exception_filter =
58      reinterpret_cast<base::win::WinProcExceptionFilter>(
59          ::GetProcAddress(::GetModuleHandle(
60                               chrome::kBrowserProcessExecutableName),
61                           "CrashForException"));
62  exception_filter = base::win::SetWinProcExceptionFilter(exception_filter);
63  DCHECK(!exception_filter);
64}
65
66// BrowserUsageUpdater --------------------------------------------------------
67// This class' job is to update the registry 'dr' value every 24 hours
68// that way google update can accurately track browser usage without
69// undercounting users that do not close chrome for long periods of time.
70class BrowserUsageUpdater : public Task {
71 public:
72  virtual ~BrowserUsageUpdater() {}
73
74  virtual void Run() OVERRIDE {
75    if (UpdateUsageRegKey())
76      Track();
77  }
78
79  static void Track() {
80    BrowserThread::PostDelayedTask(
81        BrowserThread::FILE,
82        FROM_HERE, new BrowserUsageUpdater,
83        base::TimeDelta::FromHours(24).InMillisecondsRoundedUp());
84  }
85
86 private:
87  bool UpdateUsageRegKey() {
88    FilePath module_dir;
89    if (!PathService::Get(base::DIR_MODULE, &module_dir))
90      return false;
91    bool system_level =
92        !InstallUtil::IsPerUserInstall(module_dir.value().c_str());
93    return GoogleUpdateSettings::UpdateDidRunState(true, system_level);
94  }
95};
96
97}  // namespace
98
99void DidEndMainMessageLoop() {
100  OleUninitialize();
101}
102
103void RecordBreakpadStatusUMA(MetricsService* metrics) {
104  DWORD len = ::GetEnvironmentVariableW(
105      ASCIIToWide(env_vars::kNoOOBreakpad).c_str() , NULL, 0);
106  metrics->RecordBreakpadRegistration((len == 0));
107  metrics->RecordBreakpadHasDebugger(TRUE == ::IsDebuggerPresent());
108}
109
110void WarnAboutMinimumSystemRequirements() {
111  if (base::win::GetVersion() < base::win::VERSION_XP) {
112    // Display a warning message if the user is running chrome on Windows 2000.
113    const string16 text =
114        l10n_util::GetStringUTF16(IDS_UNSUPPORTED_OS_PRE_WIN_XP);
115    const string16 caption = l10n_util::GetStringUTF16(IDS_PRODUCT_NAME);
116    ui::MessageBox(NULL, text, caption, MB_OK | MB_ICONWARNING | MB_TOPMOST);
117  }
118}
119
120void RecordBrowserStartupTime() {
121  // Calculate the time that has elapsed from our own process creation.
122  FILETIME creation_time = {};
123  FILETIME ignore = {};
124  ::GetProcessTimes(::GetCurrentProcess(), &creation_time, &ignore, &ignore,
125      &ignore);
126
127  base::TimeDelta elapsed_from_startup =
128      base::Time::Now() - base::Time::FromFileTime(creation_time);
129
130  // Record the time to present in a histogram.
131  UMA_HISTOGRAM_MEDIUM_TIMES("Startup.BrowserMessageLoopStartTime",
132                             elapsed_from_startup);
133}
134
135int AskForUninstallConfirmation() {
136  int ret = ResultCodes::NORMAL_EXIT;
137  views::Window::CreateChromeWindow(NULL, gfx::Rect(),
138                                    new UninstallView(ret))->Show();
139  views::AcceleratorHandler accelerator_handler;
140  MessageLoopForUI::current()->Run(&accelerator_handler);
141  return ret;
142}
143
144void ShowCloseBrowserFirstMessageBox() {
145  const string16 text = l10n_util::GetStringUTF16(IDS_UNINSTALL_CLOSE_APP);
146  const string16 caption = l10n_util::GetStringUTF16(IDS_PRODUCT_NAME);
147  const UINT flags = MB_OK | MB_ICONWARNING | MB_TOPMOST;
148  ui::MessageBox(NULL, text, caption, flags);
149}
150
151int DoUninstallTasks(bool chrome_still_running) {
152  // We want to show a warning to user (and exit) if Chrome is already running
153  // *before* we show the uninstall confirmation dialog box. But while the
154  // uninstall confirmation dialog is up, user might start Chrome, so we
155  // check once again after user acknowledges Uninstall dialog.
156  if (chrome_still_running) {
157    ShowCloseBrowserFirstMessageBox();
158    return ResultCodes::UNINSTALL_CHROME_ALIVE;
159  }
160  int ret = AskForUninstallConfirmation();
161  if (browser_util::IsBrowserAlreadyRunning()) {
162    ShowCloseBrowserFirstMessageBox();
163    return ResultCodes::UNINSTALL_CHROME_ALIVE;
164  }
165
166  if (ret != ResultCodes::UNINSTALL_USER_CANCEL) {
167    // The following actions are just best effort.
168    VLOG(1) << "Executing uninstall actions";
169    if (!FirstRun::RemoveSentinel())
170      VLOG(1) << "Failed to delete sentinel file.";
171    // We want to remove user level shortcuts and we only care about the ones
172    // created by us and not by the installer so |alternate| is false.
173    BrowserDistribution* dist = BrowserDistribution::GetDistribution();
174    if (!ShellUtil::RemoveChromeDesktopShortcut(dist, ShellUtil::CURRENT_USER,
175                                                false))
176      VLOG(1) << "Failed to delete desktop shortcut.";
177    if (!ShellUtil::RemoveChromeQuickLaunchShortcut(dist,
178                                                    ShellUtil::CURRENT_USER))
179      VLOG(1) << "Failed to delete quick launch shortcut.";
180  }
181  return ret;
182}
183
184// Prepares the localized strings that are going to be displayed to
185// the user if the browser process dies. These strings are stored in the
186// environment block so they are accessible in the early stages of the
187// chrome executable's lifetime.
188void PrepareRestartOnCrashEnviroment(const CommandLine& parsed_command_line) {
189  // Clear this var so child processes don't show the dialog by default.
190  scoped_ptr<base::Environment> env(base::Environment::Create());
191  env->UnSetVar(env_vars::kShowRestart);
192
193  // For non-interactive tests we don't restart on crash.
194  if (env->HasVar(env_vars::kHeadless))
195    return;
196
197  // If the known command-line test options are used we don't create the
198  // environment block which means we don't get the restart dialog.
199  if (parsed_command_line.HasSwitch(switches::kBrowserCrashTest) ||
200      parsed_command_line.HasSwitch(switches::kBrowserAssertTest) ||
201      parsed_command_line.HasSwitch(switches::kNoErrorDialogs))
202    return;
203
204  // The encoding we use for the info is "title|context|direction" where
205  // direction is either env_vars::kRtlLocale or env_vars::kLtrLocale depending
206  // on the current locale.
207  string16 dlg_strings(l10n_util::GetStringUTF16(IDS_CRASH_RECOVERY_TITLE));
208  dlg_strings.push_back('|');
209  string16 adjusted_string(
210      l10n_util::GetStringUTF16(IDS_CRASH_RECOVERY_CONTENT));
211  base::i18n::AdjustStringForLocaleDirection(&adjusted_string);
212  dlg_strings.append(adjusted_string);
213  dlg_strings.push_back('|');
214  dlg_strings.append(ASCIIToUTF16(
215      base::i18n::IsRTL() ? env_vars::kRtlLocale : env_vars::kLtrLocale));
216
217  env->SetVar(env_vars::kRestartInfo, UTF16ToUTF8(dlg_strings));
218}
219
220bool RegisterApplicationRestart(const CommandLine& parsed_command_line) {
221  DCHECK(base::win::GetVersion() >= base::win::VERSION_VISTA);
222  base::ScopedNativeLibrary library(FilePath(L"kernel32.dll"));
223  // Get the function pointer for RegisterApplicationRestart.
224  RegisterApplicationRestartProc register_application_restart =
225      static_cast<RegisterApplicationRestartProc>(
226          library.GetFunctionPointer("RegisterApplicationRestart"));
227  if (!register_application_restart)
228    return false;
229
230  // The Windows Restart Manager expects a string of command line flags only,
231  // without the program.
232  CommandLine command_line(CommandLine::NO_PROGRAM);
233  command_line.AppendSwitches(parsed_command_line);
234  command_line.AppendArgs(parsed_command_line);
235  // Ensure restore last session is set.
236  if (!command_line.HasSwitch(switches::kRestoreLastSession))
237    command_line.AppendSwitch(switches::kRestoreLastSession);
238
239  // Restart Chrome if the computer is restarted as the result of an update.
240  // This could be extended to handle crashes, hangs, and patches.
241  HRESULT hr = register_application_restart(
242      command_line.command_line_string().c_str(),
243      RESTART_NO_CRASH | RESTART_NO_HANG | RESTART_NO_PATCH);
244  DCHECK(SUCCEEDED(hr)) << "RegisterApplicationRestart failed.";
245  return SUCCEEDED(hr);
246}
247
248// This method handles the --hide-icons and --show-icons command line options
249// for chrome that get triggered by Windows from registry entries
250// HideIconsCommand & ShowIconsCommand. Chrome doesn't support hide icons
251// functionality so we just ask the users if they want to uninstall Chrome.
252int HandleIconsCommands(const CommandLine& parsed_command_line) {
253  if (parsed_command_line.HasSwitch(switches::kHideIcons)) {
254    string16 cp_applet;
255    base::win::Version version = base::win::GetVersion();
256    if (version >= base::win::VERSION_VISTA) {
257      cp_applet.assign(L"Programs and Features");  // Windows Vista and later.
258    } else if (version >= base::win::VERSION_XP) {
259      cp_applet.assign(L"Add/Remove Programs");  // Windows XP.
260    } else {
261      return ResultCodes::UNSUPPORTED_PARAM;  // Not supported
262    }
263
264    const string16 msg =
265        l10n_util::GetStringFUTF16(IDS_HIDE_ICONS_NOT_SUPPORTED, cp_applet);
266    const string16 caption = l10n_util::GetStringUTF16(IDS_PRODUCT_NAME);
267    const UINT flags = MB_OKCANCEL | MB_ICONWARNING | MB_TOPMOST;
268    if (IDOK == ui::MessageBox(NULL, msg, caption, flags))
269      ShellExecute(NULL, NULL, L"appwiz.cpl", NULL, NULL, SW_SHOWNORMAL);
270    return ResultCodes::NORMAL_EXIT;  // Exit as we are not launching browser.
271  }
272  // We don't hide icons so we shouldn't do anything special to show them
273  return ResultCodes::UNSUPPORTED_PARAM;
274}
275
276// Check if there is any machine level Chrome installed on the current
277// machine. If yes and the current Chrome process is user level, we do not
278// allow the user level Chrome to run. So we notify the user and uninstall
279// user level Chrome.
280bool CheckMachineLevelInstall() {
281  // TODO(tommi): Check if using the default distribution is always the right
282  // thing to do.
283  BrowserDistribution* dist = BrowserDistribution::GetDistribution();
284  scoped_ptr<Version> version(InstallUtil::GetChromeVersion(dist, true));
285  if (version.get()) {
286    FilePath exe_path;
287    PathService::Get(base::DIR_EXE, &exe_path);
288    std::wstring exe = exe_path.value();
289    FilePath user_exe_path(installer::GetChromeInstallPath(false, dist));
290    if (FilePath::CompareEqualIgnoreCase(exe, user_exe_path.value())) {
291      const string16 text =
292          l10n_util::GetStringUTF16(IDS_MACHINE_LEVEL_INSTALL_CONFLICT);
293      const string16 caption = l10n_util::GetStringUTF16(IDS_PRODUCT_NAME);
294      const UINT flags = MB_OK | MB_ICONERROR | MB_TOPMOST;
295      ui::MessageBox(NULL, text, caption, flags);
296      CommandLine uninstall_cmd(
297          InstallUtil::GetChromeUninstallCmd(false, dist->GetType()));
298      if (!uninstall_cmd.GetProgram().empty()) {
299        uninstall_cmd.AppendSwitch(installer::switches::kForceUninstall);
300        uninstall_cmd.AppendSwitch(
301            installer::switches::kDoNotRemoveSharedItems);
302        base::LaunchApp(uninstall_cmd, false, false, NULL);
303      }
304      return true;
305    }
306  }
307  return false;
308}
309
310// BrowserMainPartsWin ---------------------------------------------------------
311
312class BrowserMainPartsWin : public BrowserMainParts {
313 public:
314  explicit BrowserMainPartsWin(const MainFunctionParams& parameters)
315      : BrowserMainParts(parameters) {}
316
317 protected:
318  virtual void PreEarlyInitialization() {
319    // Initialize Winsock.
320    net::EnsureWinsockInit();
321  }
322
323  virtual void PreMainMessageLoopStart() {
324    OleInitialize(NULL);
325
326    // If we're running tests (ui_task is non-null), then the ResourceBundle
327    // has already been initialized.
328    if (!parameters().ui_task) {
329      // Override the configured locale with the user's preferred UI language.
330      l10n_util::OverrideLocaleWithUILanguageList();
331
332      // Make sure that we know how to handle exceptions from the message loop.
333      InitializeWindowProcExceptions();
334    }
335  }
336
337  virtual void PostMainMessageLoopStart() OVERRIDE {
338    MessageLoop::current()->PostDelayedTask(
339        FROM_HERE,
340        NewRunnableFunction(&BrowserUsageUpdater::Track),
341        base::TimeDelta::FromSeconds(30).InMillisecondsRoundedUp());
342  }
343
344 private:
345  virtual void InitializeSSL() {
346    // Use NSS for SSL by default.
347    // The default client socket factory uses NSS for SSL by default on
348    // Windows.
349    if (parsed_command_line().HasSwitch(switches::kUseSystemSSL)) {
350      net::ClientSocketFactory::UseSystemSSL();
351    } else {
352      // We want to be sure to init NSPR on the main thread.
353      crypto::EnsureNSPRInit();
354    }
355  }
356};
357
358// static
359BrowserMainParts* BrowserMainParts::CreateBrowserMainParts(
360    const MainFunctionParams& parameters) {
361  return new BrowserMainPartsWin(parameters);
362}
363