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/shell_integration.h"
6
7 #include <windows.h>
8 #include <shobjidl.h>
9 #include <propkey.h>
10 #include <propvarutil.h>
11
12 #include "base/command_line.h"
13 #include "base/file_util.h"
14 #include "base/message_loop.h"
15 #include "base/path_service.h"
16 #include "base/string_util.h"
17 #include "base/task.h"
18 #include "base/utf_string_conversions.h"
19 #include "base/win/registry.h"
20 #include "base/win/scoped_comptr.h"
21 #include "base/win/windows_version.h"
22 #include "chrome/browser/web_applications/web_app.h"
23 #include "chrome/common/chrome_constants.h"
24 #include "chrome/common/chrome_paths.h"
25 #include "chrome/common/chrome_paths_internal.h"
26 #include "chrome/common/chrome_switches.h"
27 #include "chrome/installer/util/browser_distribution.h"
28 #include "chrome/installer/util/create_reg_key_work_item.h"
29 #include "chrome/installer/util/set_reg_value_work_item.h"
30 #include "chrome/installer/util/shell_util.h"
31 #include "chrome/installer/util/util_constants.h"
32 #include "chrome/installer/util/work_item.h"
33 #include "chrome/installer/util/work_item_list.h"
34 #include "content/browser/browser_thread.h"
35
36 namespace {
37
38 // Helper function for ShellIntegration::GetAppId to generates profile id
39 // from profile path. "profile_id" is composed of sanitized basenames of
40 // user data dir and profile dir joined by a ".".
GetProfileIdFromPath(const FilePath & profile_path)41 std::wstring GetProfileIdFromPath(const FilePath& profile_path) {
42 // Return empty string if profile_path is empty
43 if (profile_path.empty())
44 return std::wstring();
45
46 FilePath default_user_data_dir;
47 // Return empty string if profile_path is in default user data
48 // dir and is the default profile.
49 if (chrome::GetDefaultUserDataDirectory(&default_user_data_dir) &&
50 profile_path.DirName() == default_user_data_dir &&
51 profile_path.BaseName().value() ==
52 ASCIIToUTF16(chrome::kNotSignedInProfile)) {
53 return std::wstring();
54 }
55
56 // Get joined basenames of user data dir and profile.
57 std::wstring basenames = profile_path.DirName().BaseName().value() +
58 L"." + profile_path.BaseName().value();
59
60 std::wstring profile_id;
61 profile_id.reserve(basenames.size());
62
63 // Generate profile_id from sanitized basenames.
64 for (size_t i = 0; i < basenames.length(); ++i) {
65 if (IsAsciiAlpha(basenames[i]) ||
66 IsAsciiDigit(basenames[i]) ||
67 basenames[i] == L'.')
68 profile_id += basenames[i];
69 }
70
71 return profile_id;
72 }
73
74 // Migrates existing chromium shortucts for Win7.
75 class MigrateChromiumShortcutsTask : public Task {
76 public:
MigrateChromiumShortcutsTask()77 MigrateChromiumShortcutsTask() { }
78
79 virtual void Run();
80
81 private:
82 void MigrateWin7Shortcuts();
83 void MigrateWin7ShortcutsInPath(const FilePath& path) const;
84
85 // Get expected app id for given chrome shortcut.
86 // Returns true if the shortcut point to chrome and expected app id is
87 // successfully derived.
88 bool GetExpectedAppId(IShellLink* shell_link,
89 std::wstring* expected_app_id) const;
90
91 // Get app id associated with given shortcut.
92 bool GetShortcutAppId(IShellLink* shell_link, std::wstring* app_id) const;
93
94 FilePath chrome_exe_;
95
96 DISALLOW_COPY_AND_ASSIGN(MigrateChromiumShortcutsTask);
97 };
98
Run()99 void MigrateChromiumShortcutsTask::Run() {
100 // This should run on the file thread.
101 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
102
103 MigrateWin7Shortcuts();
104 }
105
MigrateWin7Shortcuts()106 void MigrateChromiumShortcutsTask::MigrateWin7Shortcuts() {
107 // Get full path of chrome.
108 if (!PathService::Get(base::FILE_EXE, &chrome_exe_))
109 return;
110
111 // Locations to check for shortcuts migration.
112 static const struct {
113 int location_id;
114 const wchar_t* sub_dir;
115 } kLocations[] = {
116 {
117 base::DIR_APP_DATA,
118 L"Microsoft\\Internet Explorer\\Quick Launch\\User Pinned\\TaskBar"
119 }, {
120 chrome::DIR_USER_DESKTOP,
121 NULL
122 }, {
123 base::DIR_START_MENU,
124 NULL
125 }, {
126 base::DIR_APP_DATA,
127 L"Microsoft\\Internet Explorer\\Quick Launch\\User Pinned\\StartMenu"
128 }
129 };
130
131 for (int i = 0; i < arraysize(kLocations); ++i) {
132 FilePath path;
133 if (!PathService::Get(kLocations[i].location_id, &path)) {
134 NOTREACHED();
135 continue;
136 }
137
138 if (kLocations[i].sub_dir)
139 path = path.Append(kLocations[i].sub_dir);
140
141 MigrateWin7ShortcutsInPath(path);
142 }
143 }
144
MigrateWin7ShortcutsInPath(const FilePath & path) const145 void MigrateChromiumShortcutsTask::MigrateWin7ShortcutsInPath(
146 const FilePath& path) const {
147 // Enumerate all pinned shortcuts in the given path directly.
148 file_util::FileEnumerator shortcuts_enum(
149 path,
150 false, // not recursive
151 file_util::FileEnumerator::FILES,
152 FILE_PATH_LITERAL("*.lnk"));
153
154 for (FilePath shortcut = shortcuts_enum.Next(); !shortcut.empty();
155 shortcut = shortcuts_enum.Next()) {
156 // Load the shortcut.
157 base::win::ScopedComPtr<IShellLink> shell_link;
158 if (FAILED(shell_link.CreateInstance(CLSID_ShellLink,
159 NULL,
160 CLSCTX_INPROC_SERVER))) {
161 NOTREACHED();
162 return;
163 }
164
165 base::win::ScopedComPtr<IPersistFile> persist_file;
166 if (FAILED(persist_file.QueryFrom(shell_link)) ||
167 FAILED(persist_file->Load(shortcut.value().c_str(), STGM_READ))) {
168 NOTREACHED();
169 return;
170 }
171
172 // Get expected app id from shortcut.
173 std::wstring expected_app_id;
174 if (!GetExpectedAppId(shell_link, &expected_app_id) ||
175 expected_app_id.empty())
176 continue;
177
178 // Get existing app id from shortcut if any.
179 std::wstring existing_app_id;
180 GetShortcutAppId(shell_link, &existing_app_id);
181
182 if (expected_app_id != existing_app_id) {
183 file_util::UpdateShortcutLink(NULL,
184 shortcut.value().c_str(),
185 NULL,
186 NULL,
187 NULL,
188 NULL,
189 0,
190 expected_app_id.c_str());
191 }
192 }
193 }
194
GetExpectedAppId(IShellLink * shell_link,std::wstring * expected_app_id) const195 bool MigrateChromiumShortcutsTask::GetExpectedAppId(
196 IShellLink* shell_link,
197 std::wstring* expected_app_id) const {
198 DCHECK(shell_link);
199 DCHECK(expected_app_id);
200
201 expected_app_id->clear();
202
203 // Check if the shortcut points to chrome_exe.
204 std::wstring source;
205 if (FAILED(shell_link->GetPath(WriteInto(&source, MAX_PATH),
206 MAX_PATH,
207 NULL,
208 SLGP_RAWPATH)) ||
209 lstrcmpi(chrome_exe_.value().c_str(), source.c_str()))
210 return false;
211
212 std::wstring arguments;
213 if (FAILED(shell_link->GetArguments(WriteInto(&arguments, MAX_PATH),
214 MAX_PATH)))
215 return false;
216
217 // Get expected app id from shortcut command line.
218 CommandLine command_line = CommandLine::FromString(StringPrintf(
219 L"\"%ls\" %ls", source.c_str(), arguments.c_str()));
220
221 FilePath profile_path;
222 if (command_line.HasSwitch(switches::kUserDataDir)) {
223 profile_path =
224 command_line.GetSwitchValuePath(switches::kUserDataDir).AppendASCII(
225 chrome::kNotSignedInProfile);
226 }
227
228 std::wstring app_name;
229 if (command_line.HasSwitch(switches::kApp)) {
230 app_name = UTF8ToWide(web_app::GenerateApplicationNameFromURL(
231 GURL(command_line.GetSwitchValueASCII(switches::kApp))));
232 } else if (command_line.HasSwitch(switches::kAppId)) {
233 app_name = UTF8ToWide(web_app::GenerateApplicationNameFromExtensionId(
234 command_line.GetSwitchValueASCII(switches::kAppId)));
235 } else {
236 app_name = BrowserDistribution::GetDistribution()->GetBrowserAppId();
237 }
238
239 expected_app_id->assign(ShellIntegration::GetAppId(app_name, profile_path));
240 return true;
241 }
242
GetShortcutAppId(IShellLink * shell_link,std::wstring * app_id) const243 bool MigrateChromiumShortcutsTask::GetShortcutAppId(
244 IShellLink* shell_link,
245 std::wstring* app_id) const {
246 DCHECK(shell_link);
247 DCHECK(app_id);
248
249 app_id->clear();
250
251 base::win::ScopedComPtr<IPropertyStore> property_store;
252 if (FAILED(property_store.QueryFrom(shell_link)))
253 return false;
254
255 PROPVARIANT appid_value;
256 PropVariantInit(&appid_value);
257 if (FAILED(property_store->GetValue(PKEY_AppUserModel_ID,
258 &appid_value)))
259 return false;
260
261 if (appid_value.vt == VT_LPWSTR ||
262 appid_value.vt == VT_BSTR)
263 app_id->assign(appid_value.pwszVal);
264
265 PropVariantClear(&appid_value);
266 return true;
267 }
268
269 };
270
SetAsDefaultBrowser()271 bool ShellIntegration::SetAsDefaultBrowser() {
272 FilePath chrome_exe;
273 if (!PathService::Get(base::FILE_EXE, &chrome_exe)) {
274 LOG(ERROR) << "Error getting app exe path";
275 return false;
276 }
277
278 // From UI currently we only allow setting default browser for current user.
279 BrowserDistribution* dist = BrowserDistribution::GetDistribution();
280 if (!ShellUtil::MakeChromeDefault(dist, ShellUtil::CURRENT_USER,
281 chrome_exe.value(), true)) {
282 LOG(ERROR) << "Chrome could not be set as default browser.";
283 return false;
284 }
285
286 VLOG(1) << "Chrome registered as default browser.";
287 return true;
288 }
289
IsDefaultBrowser()290 ShellIntegration::DefaultBrowserState ShellIntegration::IsDefaultBrowser() {
291 // First determine the app path. If we can't determine what that is, we have
292 // bigger fish to fry...
293 FilePath app_path;
294 if (!PathService::Get(base::FILE_EXE, &app_path)) {
295 LOG(ERROR) << "Error getting app exe path";
296 return UNKNOWN_DEFAULT_BROWSER;
297 }
298 // When we check for default browser we don't necessarily want to count file
299 // type handlers and icons as having changed the default browser status,
300 // since the user may have changed their shell settings to cause HTML files
301 // to open with a text editor for example. We also don't want to aggressively
302 // claim FTP, since the user may have a separate FTP client. It is an open
303 // question as to how to "heal" these settings. Perhaps the user should just
304 // re-run the installer or run with the --set-default-browser command line
305 // flag. There is doubtless some other key we can hook into to cause "Repair"
306 // to show up in Add/Remove programs for us.
307 const std::wstring kChromeProtocols[] = {L"http", L"https"};
308
309 if (base::win::GetVersion() >= base::win::VERSION_VISTA) {
310 IApplicationAssociationRegistration* pAAR;
311 HRESULT hr = CoCreateInstance(CLSID_ApplicationAssociationRegistration,
312 NULL, CLSCTX_INPROC, __uuidof(IApplicationAssociationRegistration),
313 (void**)&pAAR);
314 if (!SUCCEEDED(hr))
315 return NOT_DEFAULT_BROWSER;
316
317 BrowserDistribution* dist = BrowserDistribution::GetDistribution();
318 std::wstring app_name = dist->GetApplicationName();
319 // If a user specific default browser entry exists, we check for that
320 // app name being default. If not, then default browser is just called
321 // Google Chrome or Chromium so we do not append suffix to app name.
322 std::wstring suffix;
323 if (ShellUtil::GetUserSpecificDefaultBrowserSuffix(dist, &suffix))
324 app_name += suffix;
325
326 for (int i = 0; i < _countof(kChromeProtocols); i++) {
327 BOOL result = TRUE;
328 hr = pAAR->QueryAppIsDefault(kChromeProtocols[i].c_str(), AT_URLPROTOCOL,
329 AL_EFFECTIVE, app_name.c_str(), &result);
330 if (!SUCCEEDED(hr) || result == FALSE) {
331 pAAR->Release();
332 return NOT_DEFAULT_BROWSER;
333 }
334 }
335 pAAR->Release();
336 } else {
337 std::wstring short_app_path;
338 GetShortPathName(app_path.value().c_str(),
339 WriteInto(&short_app_path, MAX_PATH),
340 MAX_PATH);
341
342 // open command for protocol associations
343 for (int i = 0; i < _countof(kChromeProtocols); i++) {
344 // Check in HKEY_CLASSES_ROOT that is the result of merge between
345 // HKLM and HKCU
346 HKEY root_key = HKEY_CLASSES_ROOT;
347 // Check <protocol>\shell\open\command
348 std::wstring key_path(kChromeProtocols[i] + ShellUtil::kRegShellOpen);
349 base::win::RegKey key(root_key, key_path.c_str(), KEY_READ);
350 std::wstring value;
351 if (!key.Valid() || (key.ReadValue(L"", &value) != ERROR_SUCCESS))
352 return NOT_DEFAULT_BROWSER;
353 // Need to normalize path in case it's been munged.
354 CommandLine command_line = CommandLine::FromString(value);
355 std::wstring short_path;
356 GetShortPathName(command_line.GetProgram().value().c_str(),
357 WriteInto(&short_path, MAX_PATH), MAX_PATH);
358 if (!FilePath::CompareEqualIgnoreCase(short_path, short_app_path))
359 return NOT_DEFAULT_BROWSER;
360 }
361 }
362 return IS_DEFAULT_BROWSER;
363 }
364
365 // There is no reliable way to say which browser is default on a machine (each
366 // browser can have some of the protocols/shortcuts). So we look for only HTTP
367 // protocol handler. Even this handler is located at different places in
368 // registry on XP and Vista:
369 // - HKCR\http\shell\open\command (XP)
370 // - HKCU\Software\Microsoft\Windows\Shell\Associations\UrlAssociations\
371 // http\UserChoice (Vista)
372 // This method checks if Firefox is defualt browser by checking these
373 // locations and returns true if Firefox traces are found there. In case of
374 // error (or if Firefox is not found)it returns the default value which
375 // is false.
IsFirefoxDefaultBrowser()376 bool ShellIntegration::IsFirefoxDefaultBrowser() {
377 bool ff_default = false;
378 if (base::win::GetVersion() >= base::win::VERSION_VISTA) {
379 std::wstring app_cmd;
380 base::win::RegKey key(HKEY_CURRENT_USER,
381 ShellUtil::kRegVistaUrlPrefs, KEY_READ);
382 if (key.Valid() && (key.ReadValue(L"Progid", &app_cmd) == ERROR_SUCCESS) &&
383 app_cmd == L"FirefoxURL")
384 ff_default = true;
385 } else {
386 std::wstring key_path(L"http");
387 key_path.append(ShellUtil::kRegShellOpen);
388 base::win::RegKey key(HKEY_CLASSES_ROOT, key_path.c_str(), KEY_READ);
389 std::wstring app_cmd;
390 if (key.Valid() && (key.ReadValue(L"", &app_cmd) == ERROR_SUCCESS) &&
391 std::wstring::npos != StringToLowerASCII(app_cmd).find(L"firefox"))
392 ff_default = true;
393 }
394 return ff_default;
395 }
396
GetAppId(const std::wstring & app_name,const FilePath & profile_path)397 std::wstring ShellIntegration::GetAppId(const std::wstring& app_name,
398 const FilePath& profile_path) {
399 std::wstring app_id(app_name);
400
401 std::wstring profile_id(GetProfileIdFromPath(profile_path));
402 if (!profile_id.empty()) {
403 app_id += L".";
404 app_id += profile_id;
405 }
406
407 // App id should be less than 128 chars.
408 DCHECK(app_id.length() < 128);
409 return app_id;
410 }
411
GetChromiumAppId(const FilePath & profile_path)412 std::wstring ShellIntegration::GetChromiumAppId(const FilePath& profile_path) {
413 return GetAppId(BrowserDistribution::GetDistribution()->GetBrowserAppId(),
414 profile_path);
415 }
416
MigrateChromiumShortcuts()417 void ShellIntegration::MigrateChromiumShortcuts() {
418 if (base::win::GetVersion() < base::win::VERSION_WIN7)
419 return;
420
421 BrowserThread::PostTask(
422 BrowserThread::FILE, FROM_HERE, new MigrateChromiumShortcutsTask());
423 }
424