1 // Copyright (c) 2012 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/browser/shell_integration.h"
10 #include <propkey.h> // Needs to come after shobjidl.h.
12 #include "base/bind.h"
13 #include "base/command_line.h"
14 #include "base/files/file_enumerator.h"
15 #include "base/files/file_util.h"
16 #include "base/message_loop/message_loop.h"
17 #include "base/path_service.h"
18 #include "base/strings/string_number_conversions.h"
19 #include "base/strings/string_util.h"
20 #include "base/strings/stringprintf.h"
21 #include "base/strings/utf_string_conversions.h"
22 #include "base/win/registry.h"
23 #include "base/win/scoped_comptr.h"
24 #include "base/win/scoped_propvariant.h"
25 #include "base/win/shortcut.h"
26 #include "base/win/windows_version.h"
27 #include "chrome/browser/policy/policy_path_parser.h"
28 #include "chrome/browser/web_applications/web_app.h"
29 #include "chrome/common/chrome_constants.h"
30 #include "chrome/common/chrome_paths_internal.h"
31 #include "chrome/common/chrome_switches.h"
32 #include "chrome/installer/setup/setup_util.h"
33 #include "chrome/installer/util/browser_distribution.h"
34 #include "chrome/installer/util/create_reg_key_work_item.h"
35 #include "chrome/installer/util/install_util.h"
36 #include "chrome/installer/util/set_reg_value_work_item.h"
37 #include "chrome/installer/util/shell_util.h"
38 #include "chrome/installer/util/util_constants.h"
39 #include "chrome/installer/util/work_item.h"
40 #include "chrome/installer/util/work_item_list.h"
41 #include "content/public/browser/browser_thread.h"
43 using content::BrowserThread
;
47 const wchar_t kAppListAppNameSuffix
[] = L
"AppList";
49 // Helper function for ShellIntegration::GetAppId to generates profile id
50 // from profile path. "profile_id" is composed of sanitized basenames of
51 // user data dir and profile dir joined by a ".".
52 base::string16
GetProfileIdFromPath(const base::FilePath
& profile_path
) {
53 // Return empty string if profile_path is empty
54 if (profile_path
.empty())
55 return base::string16();
57 base::FilePath default_user_data_dir
;
58 // Return empty string if profile_path is in default user data
59 // dir and is the default profile.
60 if (chrome::GetDefaultUserDataDirectory(&default_user_data_dir
) &&
61 profile_path
.DirName() == default_user_data_dir
&&
62 profile_path
.BaseName().value() ==
63 base::ASCIIToUTF16(chrome::kInitialProfile
)) {
64 return base::string16();
67 // Get joined basenames of user data dir and profile.
68 base::string16 basenames
= profile_path
.DirName().BaseName().value() +
69 L
"." + profile_path
.BaseName().value();
71 base::string16 profile_id
;
72 profile_id
.reserve(basenames
.size());
74 // Generate profile_id from sanitized basenames.
75 for (size_t i
= 0; i
< basenames
.length(); ++i
) {
76 if (base::IsAsciiAlpha(basenames
[i
]) ||
77 base::IsAsciiDigit(basenames
[i
]) ||
79 profile_id
+= basenames
[i
];
85 base::string16
GetAppListAppName() {
86 BrowserDistribution
* dist
= BrowserDistribution::GetDistribution();
87 base::string16
app_name(dist
->GetBaseAppId());
88 app_name
.append(kAppListAppNameSuffix
);
92 // Gets expected app id for given Chrome (based on |command_line| and
93 // |is_per_user_install|).
94 base::string16
GetExpectedAppId(const base::CommandLine
& command_line
,
95 bool is_per_user_install
) {
96 base::FilePath user_data_dir
;
97 if (command_line
.HasSwitch(switches::kUserDataDir
))
98 user_data_dir
= command_line
.GetSwitchValuePath(switches::kUserDataDir
);
100 chrome::GetDefaultUserDataDirectory(&user_data_dir
);
101 // Adjust with any policy that overrides any other way to set the path.
102 policy::path_parser::CheckUserDataDirPolicy(&user_data_dir
);
103 DCHECK(!user_data_dir
.empty());
105 base::FilePath profile_subdir
;
106 if (command_line
.HasSwitch(switches::kProfileDirectory
)) {
108 command_line
.GetSwitchValuePath(switches::kProfileDirectory
);
111 base::FilePath(base::ASCIIToUTF16(chrome::kInitialProfile
));
113 DCHECK(!profile_subdir
.empty());
115 base::FilePath profile_path
= user_data_dir
.Append(profile_subdir
);
116 base::string16 app_name
;
117 if (command_line
.HasSwitch(switches::kApp
)) {
118 app_name
= base::UTF8ToUTF16(web_app::GenerateApplicationNameFromURL(
119 GURL(command_line
.GetSwitchValueASCII(switches::kApp
))));
120 } else if (command_line
.HasSwitch(switches::kAppId
)) {
121 app_name
= base::UTF8ToUTF16(
122 web_app::GenerateApplicationNameFromExtensionId(
123 command_line
.GetSwitchValueASCII(switches::kAppId
)));
124 } else if (command_line
.HasSwitch(switches::kShowAppList
)) {
125 app_name
= GetAppListAppName();
127 BrowserDistribution
* dist
= BrowserDistribution::GetDistribution();
128 app_name
= ShellUtil::GetBrowserModelId(dist
, is_per_user_install
);
130 DCHECK(!app_name
.empty());
132 return ShellIntegration::GetAppModelIdForProfile(app_name
, profile_path
);
135 void MigrateChromiumShortcutsCallback() {
136 // This should run on the file thread.
137 DCHECK_CURRENTLY_ON(BrowserThread::FILE);
139 // Get full path of chrome.
140 base::FilePath chrome_exe
;
141 if (!PathService::Get(base::FILE_EXE
, &chrome_exe
))
144 // Locations to check for shortcuts migration.
145 static const struct {
147 const wchar_t* sub_dir
;
150 base::DIR_TASKBAR_PINS
,
153 base::DIR_USER_DESKTOP
,
156 base::DIR_START_MENU
,
160 L
"Microsoft\\Internet Explorer\\Quick Launch\\User Pinned\\StartMenu"
164 for (int i
= 0; i
< arraysize(kLocations
); ++i
) {
166 if (!PathService::Get(kLocations
[i
].location_id
, &path
)) {
171 if (kLocations
[i
].sub_dir
)
172 path
= path
.Append(kLocations
[i
].sub_dir
);
174 bool check_dual_mode
= kLocations
[i
].location_id
== base::DIR_START_MENU
||
175 kLocations
[i
].location_id
== base::DIR_TASKBAR_PINS
;
176 ShellIntegration::MigrateShortcutsInPathInternal(chrome_exe
, path
,
181 // Windows 8 introduced a new protocol->executable binding system which cannot
182 // be retrieved in the HKCR registry subkey method implemented below. We call
183 // AssocQueryString with the new Win8-only flag ASSOCF_IS_PROTOCOL instead.
184 base::string16
GetAppForProtocolUsingAssocQuery(const GURL
& url
) {
185 base::string16 url_scheme
= base::ASCIIToUTF16(url
.scheme());
186 // Don't attempt to query protocol association on an empty string.
187 if (url_scheme
.empty())
188 return base::string16();
190 // Query AssocQueryString for a human-readable description of the program
191 // that will be invoked given the provided URL spec. This is used only to
192 // populate the external protocol dialog box the user sees when invoking
193 // an unknown external protocol.
194 wchar_t out_buffer
[1024];
195 DWORD buffer_size
= arraysize(out_buffer
);
196 HRESULT hr
= AssocQueryString(ASSOCF_IS_PROTOCOL
,
197 ASSOCSTR_FRIENDLYAPPNAME
,
203 DLOG(WARNING
) << "AssocQueryString failed!";
204 return base::string16();
206 return base::string16(out_buffer
);
209 base::string16
GetAppForProtocolUsingRegistry(const GURL
& url
) {
210 const base::string16 cmd_key_path
=
211 base::ASCIIToUTF16(url
.scheme() + "\\shell\\open\\command");
212 base::win::RegKey
cmd_key(HKEY_CLASSES_ROOT
,
213 cmd_key_path
.c_str(),
215 base::string16 application_to_launch
;
216 if (cmd_key
.ReadValue(NULL
, &application_to_launch
) == ERROR_SUCCESS
) {
217 const base::string16 url_spec
=
218 base::ASCIIToUTF16(url
.possibly_invalid_spec());
219 base::ReplaceSubstringsAfterOffset(&application_to_launch
,
223 return application_to_launch
;
225 return base::string16();
229 ShellIntegration::DefaultWebClientState
230 GetDefaultWebClientStateFromShellUtilDefaultState(
231 ShellUtil::DefaultState default_state
) {
232 switch (default_state
) {
233 case ShellUtil::NOT_DEFAULT
:
234 return ShellIntegration::NOT_DEFAULT
;
235 case ShellUtil::IS_DEFAULT
:
236 return ShellIntegration::IS_DEFAULT
;
238 DCHECK_EQ(ShellUtil::UNKNOWN_DEFAULT
, default_state
);
239 return ShellIntegration::UNKNOWN_DEFAULT
;
245 ShellIntegration::DefaultWebClientSetPermission
246 ShellIntegration::CanSetAsDefaultBrowser() {
247 BrowserDistribution
* distribution
= BrowserDistribution::GetDistribution();
248 if (distribution
->GetDefaultBrowserControlPolicy() !=
249 BrowserDistribution::DEFAULT_BROWSER_FULL_CONTROL
)
250 return SET_DEFAULT_NOT_ALLOWED
;
252 if (ShellUtil::CanMakeChromeDefaultUnattended())
253 return SET_DEFAULT_UNATTENDED
;
255 return SET_DEFAULT_INTERACTIVE
;
258 bool ShellIntegration::SetAsDefaultBrowser() {
259 base::FilePath chrome_exe
;
260 if (!PathService::Get(base::FILE_EXE
, &chrome_exe
)) {
261 LOG(ERROR
) << "Error getting app exe path";
265 // From UI currently we only allow setting default browser for current user.
266 BrowserDistribution
* dist
= BrowserDistribution::GetDistribution();
267 if (!ShellUtil::MakeChromeDefault(dist
, ShellUtil::CURRENT_USER
, chrome_exe
,
268 true /* elevate_if_not_admin */)) {
269 LOG(ERROR
) << "Chrome could not be set as default browser.";
273 VLOG(1) << "Chrome registered as default browser.";
277 bool ShellIntegration::SetAsDefaultProtocolClient(const std::string
& protocol
) {
278 if (protocol
.empty())
281 base::FilePath chrome_exe
;
282 if (!PathService::Get(base::FILE_EXE
, &chrome_exe
)) {
283 LOG(ERROR
) << "Error getting app exe path";
287 base::string16
wprotocol(base::UTF8ToUTF16(protocol
));
288 BrowserDistribution
* dist
= BrowserDistribution::GetDistribution();
289 if (!ShellUtil::MakeChromeDefaultProtocolClient(dist
, chrome_exe
,
291 LOG(ERROR
) << "Chrome could not be set as default handler for "
296 VLOG(1) << "Chrome registered as default handler for " << protocol
<< ".";
300 bool ShellIntegration::SetAsDefaultBrowserInteractive() {
301 base::FilePath chrome_exe
;
302 if (!PathService::Get(base::FILE_EXE
, &chrome_exe
)) {
303 NOTREACHED() << "Error getting app exe path";
307 BrowserDistribution
* dist
= BrowserDistribution::GetDistribution();
308 if (!ShellUtil::ShowMakeChromeDefaultSystemUI(dist
, chrome_exe
)) {
309 LOG(ERROR
) << "Failed to launch the set-default-browser Windows UI.";
313 VLOG(1) << "Set-default-browser Windows UI completed.";
317 bool ShellIntegration::SetAsDefaultProtocolClientInteractive(
318 const std::string
& protocol
) {
319 base::FilePath chrome_exe
;
320 if (!PathService::Get(base::FILE_EXE
, &chrome_exe
)) {
321 NOTREACHED() << "Error getting app exe path";
325 BrowserDistribution
* dist
= BrowserDistribution::GetDistribution();
326 base::string16
wprotocol(base::UTF8ToUTF16(protocol
));
327 if (!ShellUtil::ShowMakeChromeDefaultProtocolClientSystemUI(dist
, chrome_exe
,
329 LOG(ERROR
) << "Failed to launch the set-default-client Windows UI.";
333 VLOG(1) << "Set-default-client Windows UI completed.";
337 bool ShellIntegration::IsElevationNeededForSettingDefaultProtocolClient() {
338 return base::win::GetVersion() < base::win::VERSION_WIN8
;
341 ShellIntegration::DefaultWebClientState
ShellIntegration::GetDefaultBrowser() {
342 return GetDefaultWebClientStateFromShellUtilDefaultState(
343 ShellUtil::GetChromeDefaultState());
346 ShellIntegration::DefaultWebClientState
347 ShellIntegration::IsDefaultProtocolClient(const std::string
& protocol
) {
348 return GetDefaultWebClientStateFromShellUtilDefaultState(
349 ShellUtil::GetChromeDefaultProtocolClientState(
350 base::UTF8ToUTF16(protocol
)));
353 base::string16
ShellIntegration::GetApplicationNameForProtocol(
355 // Windows 8 or above requires a new protocol association query.
356 if (base::win::GetVersion() >= base::win::VERSION_WIN8
)
357 return GetAppForProtocolUsingAssocQuery(url
);
359 return GetAppForProtocolUsingRegistry(url
);
362 // There is no reliable way to say which browser is default on a machine (each
363 // browser can have some of the protocols/shortcuts). So we look for only HTTP
364 // protocol handler. Even this handler is located at different places in
365 // registry on XP and Vista:
366 // - HKCR\http\shell\open\command (XP)
367 // - HKCU\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\
368 // http\UserChoice (Vista)
369 // This method checks if Firefox is defualt browser by checking these
370 // locations and returns true if Firefox traces are found there. In case of
371 // error (or if Firefox is not found)it returns the default value which
373 bool ShellIntegration::IsFirefoxDefaultBrowser() {
374 bool ff_default
= false;
375 if (base::win::GetVersion() >= base::win::VERSION_VISTA
) {
376 base::string16 app_cmd
;
377 base::win::RegKey
key(HKEY_CURRENT_USER
,
378 ShellUtil::kRegVistaUrlPrefs
, KEY_READ
);
379 if (key
.Valid() && (key
.ReadValue(L
"Progid", &app_cmd
) == ERROR_SUCCESS
) &&
380 app_cmd
== L
"FirefoxURL")
383 base::string16
key_path(L
"http");
384 key_path
.append(ShellUtil::kRegShellOpen
);
385 base::win::RegKey
key(HKEY_CLASSES_ROOT
, key_path
.c_str(), KEY_READ
);
386 base::string16 app_cmd
;
387 if (key
.Valid() && (key
.ReadValue(L
"", &app_cmd
) == ERROR_SUCCESS
) &&
388 base::string16::npos
!=
389 base::ToLowerASCII(app_cmd
).find(L
"firefox"))
395 base::string16
ShellIntegration::GetAppModelIdForProfile(
396 const base::string16
& app_name
,
397 const base::FilePath
& profile_path
) {
398 std::vector
<base::string16
> components
;
399 components
.push_back(app_name
);
400 const base::string16
profile_id(GetProfileIdFromPath(profile_path
));
401 if (!profile_id
.empty())
402 components
.push_back(profile_id
);
403 return ShellUtil::BuildAppModelId(components
);
406 base::string16
ShellIntegration::GetChromiumModelIdForProfile(
407 const base::FilePath
& profile_path
) {
408 BrowserDistribution
* dist
= BrowserDistribution::GetDistribution();
409 base::FilePath chrome_exe
;
410 if (!PathService::Get(base::FILE_EXE
, &chrome_exe
)) {
412 return dist
->GetBaseAppId();
414 return GetAppModelIdForProfile(
415 ShellUtil::GetBrowserModelId(dist
,
416 InstallUtil::IsPerUserInstall(chrome_exe
)),
420 base::string16
ShellIntegration::GetAppListAppModelIdForProfile(
421 const base::FilePath
& profile_path
) {
422 return ShellIntegration::GetAppModelIdForProfile(
423 GetAppListAppName(), profile_path
);
426 void ShellIntegration::MigrateChromiumShortcuts() {
427 if (base::win::GetVersion() < base::win::VERSION_WIN7
)
430 // This needs to happen eventually (e.g. so that the appid is fixed and the
431 // run-time Chrome icon is merged with the taskbar shortcut), but this is not
432 // urgent and shouldn't delay Chrome startup.
433 static const int64 kMigrateChromiumShortcutsDelaySeconds
= 15;
434 BrowserThread::PostDelayedTask(
435 BrowserThread::FILE, FROM_HERE
,
436 base::Bind(&MigrateChromiumShortcutsCallback
),
437 base::TimeDelta::FromSeconds(kMigrateChromiumShortcutsDelaySeconds
));
440 int ShellIntegration::MigrateShortcutsInPathInternal(
441 const base::FilePath
& chrome_exe
,
442 const base::FilePath
& path
,
443 bool check_dual_mode
) {
444 DCHECK(base::win::GetVersion() >= base::win::VERSION_WIN7
);
446 // Enumerate all pinned shortcuts in the given path directly.
447 base::FileEnumerator
shortcuts_enum(
448 path
, false, // not recursive
449 base::FileEnumerator::FILES
, FILE_PATH_LITERAL("*.lnk"));
451 bool is_per_user_install
= InstallUtil::IsPerUserInstall(chrome_exe
);
453 int shortcuts_migrated
= 0;
454 base::FilePath target_path
;
455 base::string16 arguments
;
456 base::win::ScopedPropVariant propvariant
;
457 for (base::FilePath shortcut
= shortcuts_enum
.Next(); !shortcut
.empty();
458 shortcut
= shortcuts_enum
.Next()) {
459 // TODO(gab): Use ProgramCompare instead of comparing FilePaths below once
460 // it is fixed to work with FilePaths with spaces.
461 if (!base::win::ResolveShortcut(shortcut
, &target_path
, &arguments
) ||
462 chrome_exe
!= target_path
) {
465 base::CommandLine
command_line(
466 base::CommandLine::FromString(base::StringPrintf(
467 L
"\"%ls\" %ls", target_path
.value().c_str(), arguments
.c_str())));
469 // Get the expected AppId for this Chrome shortcut.
470 base::string16
expected_app_id(
471 GetExpectedAppId(command_line
, is_per_user_install
));
472 if (expected_app_id
.empty())
475 // Load the shortcut.
476 base::win::ScopedComPtr
<IShellLink
> shell_link
;
477 base::win::ScopedComPtr
<IPersistFile
> persist_file
;
478 if (FAILED(shell_link
.CreateInstance(CLSID_ShellLink
, NULL
,
479 CLSCTX_INPROC_SERVER
)) ||
480 FAILED(persist_file
.QueryFrom(shell_link
.get())) ||
481 FAILED(persist_file
->Load(shortcut
.value().c_str(), STGM_READ
))) {
482 DLOG(WARNING
) << "Failed loading shortcut at " << shortcut
.value();
486 // Any properties that need to be updated on the shortcut will be stored in
487 // |updated_properties|.
488 base::win::ShortcutProperties updated_properties
;
490 // Validate the existing app id for the shortcut.
491 base::win::ScopedComPtr
<IPropertyStore
> property_store
;
493 if (FAILED(property_store
.QueryFrom(shell_link
.get())) ||
494 property_store
->GetValue(PKEY_AppUserModel_ID
, propvariant
.Receive()) !=
496 // When in doubt, prefer not updating the shortcut.
500 switch (propvariant
.get().vt
) {
502 // If there is no app_id set, set our app_id if one is expected.
503 if (!expected_app_id
.empty())
504 updated_properties
.set_app_id(expected_app_id
);
507 if (expected_app_id
!= base::string16(propvariant
.get().pwszVal
))
508 updated_properties
.set_app_id(expected_app_id
);
516 // Only set dual mode if the expected app id is the default app id.
517 BrowserDistribution
* dist
= BrowserDistribution::GetDistribution();
518 base::string16
default_chromium_model_id(
519 ShellUtil::GetBrowserModelId(dist
, is_per_user_install
));
520 if (check_dual_mode
&& expected_app_id
== default_chromium_model_id
) {
521 const bool dual_mode_desired
=
522 InstallUtil::ShouldInstallMetroProperties();
524 if (property_store
->GetValue(PKEY_AppUserModel_IsDualMode
,
525 propvariant
.Receive()) != S_OK
) {
526 // When in doubt, prefer to not update the shortcut.
530 switch (propvariant
.get().vt
) {
532 // If dual_mode is not set at all, make sure it gets set to true if
534 if (dual_mode_desired
)
535 updated_properties
.set_dual_mode(true);
538 // Make sure dual_mode is set as desired.
539 if ((!!propvariant
.get().boolVal
) != dual_mode_desired
)
540 updated_properties
.set_dual_mode(dual_mode_desired
);
549 persist_file
.Release();
550 shell_link
.Release();
552 // Update the shortcut if some of its properties need to be updated.
553 if (updated_properties
.options
&&
554 base::win::CreateOrUpdateShortcutLink(
555 shortcut
, updated_properties
,
556 base::win::SHORTCUT_UPDATE_EXISTING
)) {
557 ++shortcuts_migrated
;
560 return shortcuts_migrated
;
563 base::FilePath
ShellIntegration::GetStartMenuShortcut(
564 const base::FilePath
& chrome_exe
) {
565 static const int kFolderIds
[] = {
566 base::DIR_COMMON_START_MENU
,
567 base::DIR_START_MENU
,
569 BrowserDistribution
* dist
= BrowserDistribution::GetDistribution();
570 base::string16
shortcut_name(
571 dist
->GetShortcutName(BrowserDistribution::SHORTCUT_CHROME
));
572 base::FilePath shortcut
;
574 // Check both the common and the per-user Start Menu folders for system-level
576 size_t folder
= InstallUtil::IsPerUserInstall(chrome_exe
) ? 1 : 0;
577 for (; folder
< arraysize(kFolderIds
); ++folder
) {
578 if (!PathService::Get(kFolderIds
[folder
], &shortcut
)) {
583 shortcut
= shortcut
.Append(shortcut_name
).Append(shortcut_name
+
585 if (base::PathExists(shortcut
))
589 return base::FilePath();