ie_importer_win.cc revision 6e8cce623b6e4fe0c9e4af605d675dd9d0338c38
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. 4 5#include "chrome/utility/importer/ie_importer_win.h" 6 7#include <ole2.h> 8#include <intshcut.h> 9#include <shlobj.h> 10#include <urlhist.h> 11#include <wininet.h> 12 13#include <algorithm> 14#include <map> 15#include <string> 16#include <vector> 17 18#include "base/file_util.h" 19#include "base/files/file_enumerator.h" 20#include "base/files/file_path.h" 21#include "base/strings/string16.h" 22#include "base/strings/string_split.h" 23#include "base/strings/string_util.h" 24#include "base/strings/utf_string_conversions.h" 25#include "base/time/time.h" 26#include "base/win/registry.h" 27#include "base/win/scoped_co_mem.h" 28#include "base/win/scoped_comptr.h" 29#include "base/win/scoped_handle.h" 30#include "base/win/scoped_propvariant.h" 31#include "base/win/windows_version.h" 32#include "chrome/common/importer/ie_importer_utils_win.h" 33#include "chrome/common/importer/imported_bookmark_entry.h" 34#include "chrome/common/importer/imported_favicon_usage.h" 35#include "chrome/common/importer/importer_bridge.h" 36#include "chrome/common/importer/importer_data_types.h" 37#include "chrome/common/importer/importer_url_row.h" 38#include "chrome/common/importer/pstore_declarations.h" 39#include "chrome/grit/generated_resources.h" 40#include "chrome/utility/importer/favicon_reencode.h" 41#include "components/autofill/core/common/password_form.h" 42#include "ui/base/l10n/l10n_util.h" 43#include "url/gurl.h" 44#include "url/url_constants.h" 45 46namespace { 47 48// Registry key paths from which we import IE settings. 49const base::char16 kSearchScopePath[] = 50 L"Software\\Microsoft\\Internet Explorer\\SearchScopes"; 51const base::char16 kIEVersionKey[] = 52 L"Software\\Microsoft\\Internet Explorer"; 53const base::char16 kIEToolbarKey[] = 54 L"Software\\Microsoft\\Internet Explorer\\Toolbar"; 55 56// NTFS stream name of favicon image data. 57const base::char16 kFaviconStreamName[] = L":favicon:$DATA"; 58 59// A struct that hosts the information of AutoComplete data in PStore. 60struct AutoCompleteInfo { 61 base::string16 key; 62 std::vector<base::string16> data; 63 bool is_url; 64}; 65 66// Gets the creation time of the given file or directory. 67base::Time GetFileCreationTime(const base::string16& file) { 68 base::Time creation_time; 69 base::win::ScopedHandle file_handle( 70 CreateFile(file.c_str(), GENERIC_READ, 71 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, 72 NULL, OPEN_EXISTING, 73 FILE_ATTRIBUTE_NORMAL | FILE_FLAG_BACKUP_SEMANTICS, NULL)); 74 FILETIME creation_filetime; 75 if (GetFileTime(file_handle, &creation_filetime, NULL, NULL)) 76 creation_time = base::Time::FromFileTime(creation_filetime); 77 return creation_time; 78} 79 80// Safely read an object of type T from a raw sequence of bytes. 81template<typename T> 82bool BinaryRead(T* data, size_t offset, const std::vector<uint8>& blob) { 83 if (offset + sizeof(T) > blob.size()) 84 return false; 85 memcpy(data, &blob[offset], sizeof(T)); 86 return true; 87} 88 89// Safely read an ITEMIDLIST from a raw sequence of bytes. 90// 91// An ITEMIDLIST is a list of SHITEMIDs, terminated by a SHITEMID with 92// .cb = 0. Here, before simply casting &blob[offset] to LPITEMIDLIST, 93// we verify that the list structure is not overrunning the boundary of 94// the binary blob. 95LPCITEMIDLIST BinaryReadItemIDList(size_t offset, size_t idlist_size, 96 const std::vector<uint8>& blob) { 97 size_t head = 0; 98 while (true) { 99 // Use a USHORT instead of SHITEMID to avoid buffer over read. 100 USHORT id_cb; 101 if (head >= idlist_size || !BinaryRead(&id_cb, offset + head, blob)) 102 return NULL; 103 if (id_cb == 0) 104 break; 105 head += id_cb; 106 } 107 return reinterpret_cast<LPCITEMIDLIST>(&blob[offset]); 108} 109 110// Compares the two bookmarks in the order of IE's Favorites menu. 111// Returns true if rhs should come later than lhs (lhs < rhs). 112struct IEOrderBookmarkComparator { 113 bool operator()(const ImportedBookmarkEntry& lhs, 114 const ImportedBookmarkEntry& rhs) const { 115 static const uint32 kNotSorted = 0xfffffffb; // IE uses this magic value. 116 base::FilePath lhs_prefix; 117 base::FilePath rhs_prefix; 118 for (size_t i = 0; i <= lhs.path.size() && i <= rhs.path.size(); ++i) { 119 const base::FilePath::StringType lhs_i = 120 (i < lhs.path.size() ? lhs.path[i] : lhs.title + L".url"); 121 const base::FilePath::StringType rhs_i = 122 (i < rhs.path.size() ? rhs.path[i] : rhs.title + L".url"); 123 lhs_prefix = lhs_prefix.Append(lhs_i); 124 rhs_prefix = rhs_prefix.Append(rhs_i); 125 if (lhs_i == rhs_i) 126 continue; 127 // The first path element that differs between the two. 128 std::map<base::FilePath, uint32>::const_iterator lhs_iter = 129 sort_index_->find(lhs_prefix); 130 std::map<base::FilePath, uint32>::const_iterator rhs_iter = 131 sort_index_->find(rhs_prefix); 132 uint32 lhs_sort_index = (lhs_iter == sort_index_->end() ? kNotSorted 133 : lhs_iter->second); 134 uint32 rhs_sort_index = (rhs_iter == sort_index_->end() ? kNotSorted 135 : rhs_iter->second); 136 if (lhs_sort_index != rhs_sort_index) 137 return lhs_sort_index < rhs_sort_index; 138 // If they have the same sort order, sort alphabetically. 139 return lhs_i < rhs_i; 140 } 141 return lhs.path.size() < rhs.path.size(); 142 } 143 const std::map<base::FilePath, uint32>* sort_index_; 144}; 145 146// IE stores the order of the Favorites menu in registry under: 147// HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\MenuOrder\Favorites. 148// The folder hierarchy of Favorites menu is directly mapped to the key 149// hierarchy in the registry. 150// 151// If the order of the items in a folder is customized by user, the order is 152// recorded in the REG_BINARY value named "Order" of the corresponding key. 153// The content of the "Order" value is a raw binary dump of an array of the 154// following data structure 155// struct { 156// uint32 size; // Note that ITEMIDLIST is variably-sized. 157// uint32 sort_index; // 0 means this is the first item, 1 the second, ... 158// ITEMIDLIST item_id; 159// }; 160// where each item_id should correspond to a favorites link file (*.url) in 161// the current folder. 162bool ParseFavoritesOrderBlob( 163 const Importer* importer, 164 const std::vector<uint8>& blob, 165 const base::FilePath& path, 166 std::map<base::FilePath, uint32>* sort_index) WARN_UNUSED_RESULT { 167 static const int kItemCountOffset = 16; 168 static const int kItemListStartOffset = 20; 169 170 // Read the number of items. 171 uint32 item_count = 0; 172 if (!BinaryRead(&item_count, kItemCountOffset, blob)) 173 return false; 174 175 // Traverse over the items. 176 size_t base_offset = kItemListStartOffset; 177 for (uint32 i = 0; i < item_count && !importer->cancelled(); ++i) { 178 static const int kSizeOffset = 0; 179 static const int kSortIndexOffset = 4; 180 static const int kItemIDListOffset = 8; 181 182 // Read the size (number of bytes) of the current item. 183 uint32 item_size = 0; 184 if (!BinaryRead(&item_size, base_offset + kSizeOffset, blob) || 185 base_offset + item_size <= base_offset || // checking overflow 186 base_offset + item_size > blob.size()) 187 return false; 188 189 // Read the sort index of the current item. 190 uint32 item_sort_index = 0; 191 if (!BinaryRead(&item_sort_index, base_offset + kSortIndexOffset, blob)) 192 return false; 193 194 // Read the file name from the ITEMIDLIST structure. 195 LPCITEMIDLIST idlist = BinaryReadItemIDList( 196 base_offset + kItemIDListOffset, item_size - kItemIDListOffset, blob); 197 TCHAR item_filename[MAX_PATH]; 198 if (!idlist || FAILED(SHGetPathFromIDList(idlist, item_filename))) 199 return false; 200 base::FilePath item_relative_path = 201 path.Append(base::FilePath(item_filename).BaseName()); 202 203 // Record the retrieved information and go to the next item. 204 sort_index->insert(std::make_pair(item_relative_path, item_sort_index)); 205 base_offset += item_size; 206 } 207 return true; 208} 209 210bool ParseFavoritesOrderRegistryTree( 211 const Importer* importer, 212 const base::win::RegKey& key, 213 const base::FilePath& path, 214 std::map<base::FilePath, uint32>* sort_index) WARN_UNUSED_RESULT { 215 // Parse the order information of the current folder. 216 DWORD blob_length = 0; 217 if (key.ReadValue(L"Order", NULL, &blob_length, NULL) == ERROR_SUCCESS) { 218 std::vector<uint8> blob(blob_length); 219 if (blob_length > 0 && 220 key.ReadValue(L"Order", reinterpret_cast<DWORD*>(&blob[0]), 221 &blob_length, NULL) == ERROR_SUCCESS) { 222 if (!ParseFavoritesOrderBlob(importer, blob, path, sort_index)) 223 return false; 224 } 225 } 226 227 // Recursively parse subfolders. 228 for (base::win::RegistryKeyIterator child(key.Handle(), L""); 229 child.Valid() && !importer->cancelled(); 230 ++child) { 231 base::win::RegKey subkey(key.Handle(), child.Name(), KEY_READ); 232 if (subkey.Valid()) { 233 base::FilePath subpath(path.Append(child.Name())); 234 if (!ParseFavoritesOrderRegistryTree(importer, subkey, subpath, 235 sort_index)) { 236 return false; 237 } 238 } 239 } 240 return true; 241} 242 243bool ParseFavoritesOrderInfo( 244 const Importer* importer, 245 std::map<base::FilePath, uint32>* sort_index) WARN_UNUSED_RESULT { 246 base::string16 key_path(importer::GetIEFavoritesOrderKey()); 247 base::win::RegKey key(HKEY_CURRENT_USER, key_path.c_str(), KEY_READ); 248 if (!key.Valid()) 249 return false; 250 return ParseFavoritesOrderRegistryTree(importer, key, base::FilePath(), 251 sort_index); 252} 253 254// Reads the sort order from registry. If failed, we don't touch the list 255// and use the default (alphabetical) order. 256void SortBookmarksInIEOrder( 257 const Importer* importer, 258 std::vector<ImportedBookmarkEntry>* bookmarks) { 259 std::map<base::FilePath, uint32> sort_index; 260 if (!ParseFavoritesOrderInfo(importer, &sort_index)) 261 return; 262 IEOrderBookmarkComparator compare = {&sort_index}; 263 std::sort(bookmarks->begin(), bookmarks->end(), compare); 264} 265 266// Reads an internet shortcut (*.url) |file| and returns a COM object 267// representing it. 268bool LoadInternetShortcut( 269 const base::string16& file, 270 base::win::ScopedComPtr<IUniformResourceLocator>* shortcut) { 271 base::win::ScopedComPtr<IUniformResourceLocator> url_locator; 272 if (FAILED(url_locator.CreateInstance(CLSID_InternetShortcut, NULL, 273 CLSCTX_INPROC_SERVER))) 274 return false; 275 276 base::win::ScopedComPtr<IPersistFile> persist_file; 277 if (FAILED(persist_file.QueryFrom(url_locator))) 278 return false; 279 280 // Loads the Internet Shortcut from persistent storage. 281 if (FAILED(persist_file->Load(file.c_str(), STGM_READ))) 282 return false; 283 284 std::swap(url_locator, *shortcut); 285 return true; 286} 287 288// Reads the URL stored in the internet shortcut. 289GURL ReadURLFromInternetShortcut(IUniformResourceLocator* url_locator) { 290 base::win::ScopedCoMem<wchar_t> url; 291 // GetURL can return S_FALSE (FAILED(S_FALSE) is false) when url == NULL. 292 return (FAILED(url_locator->GetURL(&url)) || !url) ? 293 GURL() : GURL(base::WideToUTF16(std::wstring(url))); 294} 295 296// Reads the URL of the favicon of the internet shortcut. 297GURL ReadFaviconURLFromInternetShortcut(IUniformResourceLocator* url_locator) { 298 base::win::ScopedComPtr<IPropertySetStorage> property_set_storage; 299 if (FAILED(property_set_storage.QueryFrom(url_locator))) 300 return GURL(); 301 302 base::win::ScopedComPtr<IPropertyStorage> property_storage; 303 if (FAILED(property_set_storage->Open(FMTID_Intshcut, STGM_READ, 304 property_storage.Receive()))) { 305 return GURL(); 306 } 307 308 PROPSPEC properties[] = {{PRSPEC_PROPID, PID_IS_ICONFILE}}; 309 // ReadMultiple takes a non-const array of PROPVARIANTs, but since this code 310 // only needs an array of size 1: a non-const pointer to |output| is 311 // equivalent. 312 base::win::ScopedPropVariant output; 313 // ReadMultiple can return S_FALSE (FAILED(S_FALSE) is false) when the 314 // property is not found, in which case output[0].vt is set to VT_EMPTY. 315 if (FAILED(property_storage->ReadMultiple(1, properties, output.Receive())) || 316 output.get().vt != VT_LPWSTR) 317 return GURL(); 318 return GURL(base::WideToUTF16(output.get().pwszVal)); 319} 320 321// Reads the favicon imaga data in an NTFS alternate data stream. This is where 322// IE7 and above store the data. 323bool ReadFaviconDataFromInternetShortcut(const base::string16& file, 324 std::string* data) { 325 return base::ReadFileToString( 326 base::FilePath(file + kFaviconStreamName), data); 327} 328 329// Reads the favicon imaga data in the Internet cache. IE6 doesn't hold the data 330// explicitly, but it might be found in the cache. 331bool ReadFaviconDataFromCache(const GURL& favicon_url, std::string* data) { 332 std::wstring url_wstring(base::UTF8ToWide(favicon_url.spec())); 333 DWORD info_size = 0; 334 GetUrlCacheEntryInfoEx(url_wstring.c_str(), NULL, &info_size, NULL, NULL, 335 NULL, 0); 336 if (GetLastError() != ERROR_INSUFFICIENT_BUFFER) 337 return false; 338 339 std::vector<char> buf(info_size); 340 INTERNET_CACHE_ENTRY_INFO* cache = 341 reinterpret_cast<INTERNET_CACHE_ENTRY_INFO*>(&buf[0]); 342 if (!GetUrlCacheEntryInfoEx(url_wstring.c_str(), cache, &info_size, NULL, 343 NULL, NULL, 0)) { 344 return false; 345 } 346 return base::ReadFileToString(base::FilePath(cache->lpszLocalFileName), data); 347} 348 349// Reads the binary image data of favicon of an internet shortcut file |file|. 350// |favicon_url| read by ReadFaviconURLFromInternetShortcut is also needed to 351// examine the IE cache. 352bool ReadReencodedFaviconData(const base::string16& file, 353 const GURL& favicon_url, 354 std::vector<unsigned char>* data) { 355 std::string image_data; 356 if (!ReadFaviconDataFromInternetShortcut(file, &image_data) && 357 !ReadFaviconDataFromCache(favicon_url, &image_data)) { 358 return false; 359 } 360 361 const unsigned char* ptr = 362 reinterpret_cast<const unsigned char*>(image_data.c_str()); 363 return importer::ReencodeFavicon(ptr, image_data.size(), data); 364} 365 366// Loads favicon image data and registers to |favicon_map|. 367void UpdateFaviconMap(const base::string16& url_file, 368 const GURL& url, 369 IUniformResourceLocator* url_locator, 370 std::map<GURL, ImportedFaviconUsage>* favicon_map) { 371 GURL favicon_url = ReadFaviconURLFromInternetShortcut(url_locator); 372 if (!favicon_url.is_valid()) 373 return; 374 375 std::map<GURL, ImportedFaviconUsage>::iterator it = 376 favicon_map->find(favicon_url); 377 if (it != favicon_map->end()) { 378 // Known favicon URL. 379 it->second.urls.insert(url); 380 } else { 381 // New favicon URL. Read the image data and store. 382 ImportedFaviconUsage usage; 383 if (ReadReencodedFaviconData(url_file, favicon_url, &usage.png_data)) { 384 usage.favicon_url = favicon_url; 385 usage.urls.insert(url); 386 favicon_map->insert(std::make_pair(favicon_url, usage)); 387 } 388 } 389} 390 391} // namespace 392 393// static 394// {E161255A-37C3-11D2-BCAA-00C04fD929DB} 395const GUID IEImporter::kPStoreAutocompleteGUID = { 396 0xe161255a, 0x37c3, 0x11d2, 397 { 0xbc, 0xaa, 0x00, 0xc0, 0x4f, 0xd9, 0x29, 0xdb } 398}; 399// {A79029D6-753E-4e27-B807-3D46AB1545DF} 400const GUID IEImporter::kUnittestGUID = { 401 0xa79029d6, 0x753e, 0x4e27, 402 { 0xb8, 0x7, 0x3d, 0x46, 0xab, 0x15, 0x45, 0xdf } 403}; 404 405IEImporter::IEImporter() { 406} 407 408void IEImporter::StartImport(const importer::SourceProfile& source_profile, 409 uint16 items, 410 ImporterBridge* bridge) { 411 bridge_ = bridge; 412 source_path_ = source_profile.source_path; 413 414 bridge_->NotifyStarted(); 415 416 if ((items & importer::HOME_PAGE) && !cancelled()) { 417 bridge_->NotifyItemStarted(importer::HOME_PAGE); 418 ImportHomepage(); // Doesn't have a UI item. 419 bridge_->NotifyItemEnded(importer::HOME_PAGE); 420 } 421 // The order here is important! 422 if ((items & importer::HISTORY) && !cancelled()) { 423 bridge_->NotifyItemStarted(importer::HISTORY); 424 ImportHistory(); 425 bridge_->NotifyItemEnded(importer::HISTORY); 426 } 427 if ((items & importer::FAVORITES) && !cancelled()) { 428 bridge_->NotifyItemStarted(importer::FAVORITES); 429 ImportFavorites(); 430 bridge_->NotifyItemEnded(importer::FAVORITES); 431 } 432 if ((items & importer::SEARCH_ENGINES) && !cancelled()) { 433 bridge_->NotifyItemStarted(importer::SEARCH_ENGINES); 434 ImportSearchEngines(); 435 bridge_->NotifyItemEnded(importer::SEARCH_ENGINES); 436 } 437 if ((items & importer::PASSWORDS) && !cancelled()) { 438 bridge_->NotifyItemStarted(importer::PASSWORDS); 439 // Always import IE6 passwords. 440 ImportPasswordsIE6(); 441 442 if (CurrentIEVersion() >= 7) 443 ImportPasswordsIE7(); 444 bridge_->NotifyItemEnded(importer::PASSWORDS); 445 } 446 bridge_->NotifyEnded(); 447} 448 449IEImporter::~IEImporter() { 450} 451 452void IEImporter::ImportFavorites() { 453 FavoritesInfo info; 454 if (!GetFavoritesInfo(&info)) 455 return; 456 457 BookmarkVector bookmarks; 458 std::vector<ImportedFaviconUsage> favicons; 459 ParseFavoritesFolder(info, &bookmarks, &favicons); 460 461 if (!bookmarks.empty() && !cancelled()) { 462 const base::string16& first_folder_name = 463 l10n_util::GetStringUTF16(IDS_BOOKMARK_GROUP_FROM_IE); 464 bridge_->AddBookmarks(bookmarks, first_folder_name); 465 } 466 if (!favicons.empty() && !cancelled()) 467 bridge_->SetFavicons(favicons); 468} 469 470void IEImporter::ImportHistory() { 471 const std::string kSchemes[] = {url::kHttpScheme, 472 url::kHttpsScheme, 473 url::kFtpScheme, 474 url::kFileScheme}; 475 int total_schemes = arraysize(kSchemes); 476 477 base::win::ScopedComPtr<IUrlHistoryStg2> url_history_stg2; 478 HRESULT result; 479 result = url_history_stg2.CreateInstance(CLSID_CUrlHistory, NULL, 480 CLSCTX_INPROC_SERVER); 481 if (FAILED(result)) 482 return; 483 base::win::ScopedComPtr<IEnumSTATURL> enum_url; 484 if (SUCCEEDED(result = url_history_stg2->EnumUrls(enum_url.Receive()))) { 485 std::vector<ImporterURLRow> rows; 486 STATURL stat_url; 487 ULONG fetched; 488 while (!cancelled() && 489 (result = enum_url->Next(1, &stat_url, &fetched)) == S_OK) { 490 base::string16 url_string; 491 if (stat_url.pwcsUrl) { 492 url_string = stat_url.pwcsUrl; 493 CoTaskMemFree(stat_url.pwcsUrl); 494 } 495 base::string16 title_string; 496 if (stat_url.pwcsTitle) { 497 title_string = stat_url.pwcsTitle; 498 CoTaskMemFree(stat_url.pwcsTitle); 499 } 500 501 GURL url(url_string); 502 // Skips the URLs that are invalid or have other schemes. 503 if (!url.is_valid() || 504 (std::find(kSchemes, kSchemes + total_schemes, url.scheme()) == 505 kSchemes + total_schemes)) 506 continue; 507 508 ImporterURLRow row(url); 509 row.title = title_string; 510 row.last_visit = base::Time::FromFileTime(stat_url.ftLastVisited); 511 if (stat_url.dwFlags == STATURL_QUERYFLAG_TOPLEVEL) { 512 row.visit_count = 1; 513 row.hidden = false; 514 } else { 515 row.hidden = true; 516 } 517 518 rows.push_back(row); 519 } 520 521 if (!rows.empty() && !cancelled()) { 522 bridge_->SetHistoryItems(rows, importer::VISIT_SOURCE_IE_IMPORTED); 523 } 524 } 525} 526 527void IEImporter::ImportPasswordsIE6() { 528 GUID AutocompleteGUID = kPStoreAutocompleteGUID; 529 if (!source_path_.empty()) { 530 // We supply a fake GUID for testting. 531 AutocompleteGUID = kUnittestGUID; 532 } 533 534 // The PStoreCreateInstance function retrieves an interface pointer 535 // to a storage provider. But this function has no associated import 536 // library or header file, we must call it using the LoadLibrary() 537 // and GetProcAddress() functions. 538 typedef HRESULT (WINAPI *PStoreCreateFunc)(IPStore**, DWORD, DWORD, DWORD); 539 HMODULE pstorec_dll = LoadLibrary(L"pstorec.dll"); 540 if (!pstorec_dll) 541 return; 542 PStoreCreateFunc PStoreCreateInstance = 543 (PStoreCreateFunc)GetProcAddress(pstorec_dll, "PStoreCreateInstance"); 544 if (!PStoreCreateInstance) { 545 FreeLibrary(pstorec_dll); 546 return; 547 } 548 549 base::win::ScopedComPtr<IPStore, &IID_IPStore> pstore; 550 HRESULT result = PStoreCreateInstance(pstore.Receive(), 0, 0, 0); 551 if (result != S_OK) { 552 FreeLibrary(pstorec_dll); 553 return; 554 } 555 556 std::vector<AutoCompleteInfo> ac_list; 557 558 // Enumerates AutoComplete items in the protected database. 559 base::win::ScopedComPtr<IEnumPStoreItems, &IID_IEnumPStoreItems> item; 560 result = pstore->EnumItems(0, &AutocompleteGUID, 561 &AutocompleteGUID, 0, item.Receive()); 562 if (result != PST_E_OK) { 563 pstore.Release(); 564 FreeLibrary(pstorec_dll); 565 return; 566 } 567 568 wchar_t* item_name; 569 while (!cancelled() && SUCCEEDED(item->Next(1, &item_name, 0))) { 570 DWORD length = 0; 571 unsigned char* buffer = NULL; 572 result = pstore->ReadItem(0, &AutocompleteGUID, &AutocompleteGUID, 573 item_name, &length, &buffer, NULL, 0); 574 if (SUCCEEDED(result)) { 575 AutoCompleteInfo ac; 576 ac.key = item_name; 577 base::string16 data; 578 data.insert(0, reinterpret_cast<wchar_t*>(buffer), 579 length / sizeof(wchar_t)); 580 581 // The key name is always ended with ":StringData". 582 const wchar_t kDataSuffix[] = L":StringData"; 583 size_t i = ac.key.rfind(kDataSuffix); 584 if (i != base::string16::npos && ac.key.substr(i) == kDataSuffix) { 585 ac.key.erase(i); 586 ac.is_url = (ac.key.find(L"://") != base::string16::npos); 587 ac_list.push_back(ac); 588 base::SplitString(data, L'\0', &ac_list[ac_list.size() - 1].data); 589 } 590 CoTaskMemFree(buffer); 591 } 592 CoTaskMemFree(item_name); 593 } 594 // Releases them before unload the dll. 595 item.Release(); 596 pstore.Release(); 597 FreeLibrary(pstorec_dll); 598 599 size_t i; 600 for (i = 0; i < ac_list.size(); i++) { 601 if (!ac_list[i].is_url || ac_list[i].data.size() < 2) 602 continue; 603 604 GURL url(ac_list[i].key.c_str()); 605 if (!(LowerCaseEqualsASCII(url.scheme(), url::kHttpScheme) || 606 LowerCaseEqualsASCII(url.scheme(), url::kHttpsScheme))) { 607 continue; 608 } 609 610 autofill::PasswordForm form; 611 GURL::Replacements rp; 612 rp.ClearUsername(); 613 rp.ClearPassword(); 614 rp.ClearQuery(); 615 rp.ClearRef(); 616 form.origin = url.ReplaceComponents(rp); 617 form.username_value = ac_list[i].data[0]; 618 form.password_value = ac_list[i].data[1]; 619 form.signon_realm = url.GetOrigin().spec(); 620 621 // This is not precise, because a scheme of https does not imply a valid 622 // certificate was presented; however we assign it this way so that if we 623 // import a password from IE whose scheme is https, we give it the benefit 624 // of the doubt and DONT auto-fill it unless the form appears under 625 // valid SSL conditions. 626 form.ssl_valid = url.SchemeIsSecure(); 627 628 // Goes through the list to find out the username field 629 // of the web page. 630 size_t list_it, item_it; 631 for (list_it = 0; list_it < ac_list.size(); ++list_it) { 632 if (ac_list[list_it].is_url) 633 continue; 634 635 for (item_it = 0; item_it < ac_list[list_it].data.size(); ++item_it) 636 if (ac_list[list_it].data[item_it] == form.username_value) { 637 form.username_element = ac_list[list_it].key; 638 break; 639 } 640 } 641 642 bridge_->SetPasswordForm(form); 643 } 644} 645 646void IEImporter::ImportPasswordsIE7() { 647 base::string16 key_path(importer::GetIE7PasswordsKey()); 648 base::win::RegKey key(HKEY_CURRENT_USER, key_path.c_str(), KEY_READ); 649 base::win::RegistryValueIterator reg_iterator(HKEY_CURRENT_USER, 650 key_path.c_str()); 651 importer::ImporterIE7PasswordInfo password_info; 652 while (reg_iterator.Valid() && !cancelled()) { 653 // Get the size of the encrypted data. 654 DWORD value_len = 0; 655 key.ReadValue(reg_iterator.Name(), NULL, &value_len, NULL); 656 if (value_len) { 657 // Query the encrypted data. 658 password_info.encrypted_data.resize(value_len); 659 if (key.ReadValue(reg_iterator.Name(), 660 &password_info.encrypted_data.front(), 661 &value_len, NULL) == ERROR_SUCCESS) { 662 password_info.url_hash = reg_iterator.Name(); 663 password_info.date_created = base::Time::Now(); 664 665 bridge_->AddIE7PasswordInfo(password_info); 666 } 667 } 668 669 ++reg_iterator; 670 } 671} 672 673void IEImporter::ImportSearchEngines() { 674 // On IE, search engines are stored in the registry, under: 675 // Software\Microsoft\Internet Explorer\SearchScopes 676 // Each key represents a search engine. The URL value contains the URL and 677 // the DisplayName the name. 678 typedef std::map<std::string, base::string16> SearchEnginesMap; 679 SearchEnginesMap search_engines_map; 680 for (base::win::RegistryKeyIterator key_iter(HKEY_CURRENT_USER, 681 kSearchScopePath); key_iter.Valid(); ++key_iter) { 682 base::string16 sub_key_name = kSearchScopePath; 683 sub_key_name.append(L"\\").append(key_iter.Name()); 684 base::win::RegKey sub_key(HKEY_CURRENT_USER, sub_key_name.c_str(), 685 KEY_READ); 686 base::string16 wide_url; 687 if ((sub_key.ReadValue(L"URL", &wide_url) != ERROR_SUCCESS) || 688 wide_url.empty()) { 689 VLOG(1) << "No URL for IE search engine at " << key_iter.Name(); 690 continue; 691 } 692 // For the name, we try the default value first (as Live Search uses a 693 // non displayable name in DisplayName, and the readable name under the 694 // default value). 695 base::string16 name; 696 if ((sub_key.ReadValue(NULL, &name) != ERROR_SUCCESS) || name.empty()) { 697 // Try the displayable name. 698 if ((sub_key.ReadValue(L"DisplayName", &name) != ERROR_SUCCESS) || 699 name.empty()) { 700 VLOG(1) << "No name for IE search engine at " << key_iter.Name(); 701 continue; 702 } 703 } 704 705 std::string url(base::WideToUTF8(wide_url)); 706 SearchEnginesMap::iterator t_iter = search_engines_map.find(url); 707 if (t_iter == search_engines_map.end()) { 708 // First time we see that URL. 709 GURL gurl(url); 710 if (gurl.is_valid()) { 711 t_iter = search_engines_map.insert(std::make_pair(url, name)).first; 712 } 713 } 714 } 715 // ProfileWriter::AddKeywords() requires a vector and we have a map. 716 std::vector<importer::URLKeywordInfo> url_keywords; 717 for (SearchEnginesMap::iterator i = search_engines_map.begin(); 718 i != search_engines_map.end(); ++i) { 719 importer::URLKeywordInfo url_keyword_info; 720 url_keyword_info.url = GURL(i->first); 721 url_keyword_info.display_name = i->second; 722 url_keywords.push_back(url_keyword_info); 723 } 724 bridge_->SetKeywords(url_keywords, true); 725} 726 727void IEImporter::ImportHomepage() { 728 const wchar_t* kIEHomepage = L"Start Page"; 729 const wchar_t* kIEDefaultHomepage = L"Default_Page_URL"; 730 731 base::string16 key_path(importer::GetIESettingsKey()); 732 733 base::win::RegKey key(HKEY_CURRENT_USER, key_path.c_str(), KEY_READ); 734 base::string16 homepage_url; 735 if (key.ReadValue(kIEHomepage, &homepage_url) != ERROR_SUCCESS || 736 homepage_url.empty()) 737 return; 738 739 GURL homepage = GURL(homepage_url); 740 if (!homepage.is_valid()) 741 return; 742 743 // Check to see if this is the default website and skip import. 744 base::win::RegKey keyDefault(HKEY_LOCAL_MACHINE, key_path.c_str(), KEY_READ); 745 base::string16 default_homepage_url; 746 LONG result = keyDefault.ReadValue(kIEDefaultHomepage, &default_homepage_url); 747 if (result == ERROR_SUCCESS && !default_homepage_url.empty()) { 748 if (homepage.spec() == GURL(default_homepage_url).spec()) 749 return; 750 } 751 bridge_->AddHomePage(homepage); 752} 753 754bool IEImporter::GetFavoritesInfo(IEImporter::FavoritesInfo* info) { 755 if (!source_path_.empty()) { 756 // Source path exists during testing. 757 info->path = source_path_; 758 info->path = info->path.AppendASCII("Favorites"); 759 info->links_folder = L"Links"; 760 return true; 761 } 762 763 // IE stores the favorites in the Favorites under user profile's folder. 764 wchar_t buffer[MAX_PATH]; 765 if (FAILED(SHGetFolderPath(NULL, CSIDL_FAVORITES, NULL, 766 SHGFP_TYPE_CURRENT, buffer))) 767 return false; 768 info->path = base::FilePath(buffer); 769 770 // There is a Links folder under Favorites folder in Windows Vista, but it 771 // is not recording in Vista's registry. So in Vista, we assume the Links 772 // folder is under Favorites folder since it looks like there is not name 773 // different in every language version of Windows Vista. 774 if (base::win::GetVersion() < base::win::VERSION_VISTA) { 775 // The Link folder name is stored in the registry. 776 DWORD buffer_length = sizeof(buffer); 777 base::win::RegKey reg_key(HKEY_CURRENT_USER, kIEToolbarKey, KEY_READ); 778 if (reg_key.ReadValue(L"LinksFolderName", buffer, 779 &buffer_length, NULL) != ERROR_SUCCESS) 780 return false; 781 info->links_folder = buffer; 782 } else { 783 info->links_folder = L"Links"; 784 } 785 786 return true; 787} 788 789void IEImporter::ParseFavoritesFolder( 790 const FavoritesInfo& info, 791 BookmarkVector* bookmarks, 792 std::vector<ImportedFaviconUsage>* favicons) { 793 base::FilePath file; 794 std::vector<base::FilePath::StringType> file_list; 795 base::FilePath favorites_path(info.path); 796 // Favorites path length. Make sure it doesn't include the trailing \. 797 size_t favorites_path_len = 798 favorites_path.StripTrailingSeparators().value().size(); 799 base::FileEnumerator file_enumerator( 800 favorites_path, true, base::FileEnumerator::FILES); 801 while (!(file = file_enumerator.Next()).value().empty() && !cancelled()) 802 file_list.push_back(file.value()); 803 804 // Keep the bookmarks in alphabetical order. 805 std::sort(file_list.begin(), file_list.end()); 806 807 // Map from favicon URLs to the favicon data (the binary image data and the 808 // set of bookmark URLs referring to the favicon). 809 typedef std::map<GURL, ImportedFaviconUsage> FaviconMap; 810 FaviconMap favicon_map; 811 812 for (std::vector<base::FilePath::StringType>::iterator it = file_list.begin(); 813 it != file_list.end(); ++it) { 814 base::FilePath shortcut(*it); 815 if (!LowerCaseEqualsASCII(shortcut.Extension(), ".url")) 816 continue; 817 818 // Skip the bookmark with invalid URL. 819 base::win::ScopedComPtr<IUniformResourceLocator> url_locator; 820 if (!LoadInternetShortcut(*it, &url_locator)) 821 continue; 822 GURL url = ReadURLFromInternetShortcut(url_locator); 823 if (!url.is_valid()) 824 continue; 825 // Skip default bookmarks. go.microsoft.com redirects to 826 // search.microsoft.com, and http://go.microsoft.com/fwlink/?LinkId=XXX, 827 // which URLs IE has as default, to some another sites. 828 // We expect that users will never themselves create bookmarks having this 829 // hostname. 830 if (url.host() == "go.microsoft.com") 831 continue; 832 // Read favicon. 833 UpdateFaviconMap(*it, url, url_locator, &favicon_map); 834 835 // Make the relative path from the Favorites folder, without the basename. 836 // ex. Suppose that the Favorites folder is C:\Users\Foo\Favorites. 837 // C:\Users\Foo\Favorites\Foo.url -> "" 838 // C:\Users\Foo\Favorites\Links\Bar\Baz.url -> "Links\Bar" 839 base::FilePath::StringType relative_string = 840 shortcut.DirName().value().substr(favorites_path_len); 841 if (!relative_string.empty() && 842 base::FilePath::IsSeparator(relative_string[0])) 843 relative_string = relative_string.substr(1); 844 base::FilePath relative_path(relative_string); 845 846 ImportedBookmarkEntry entry; 847 // Remove the dot, the file extension, and the directory path. 848 entry.title = shortcut.RemoveExtension().BaseName().value(); 849 entry.url = url; 850 entry.creation_time = GetFileCreationTime(*it); 851 if (!relative_path.empty()) 852 relative_path.GetComponents(&entry.path); 853 854 // Add the bookmark. 855 if (!entry.path.empty() && entry.path[0] == info.links_folder) { 856 // Bookmarks in the Link folder should be imported to the toolbar. 857 entry.in_toolbar = true; 858 } 859 bookmarks->push_back(entry); 860 } 861 862 // Reflect the menu order in IE. 863 SortBookmarksInIEOrder(this, bookmarks); 864 865 // Record favicon data. 866 for (FaviconMap::iterator iter = favicon_map.begin(); 867 iter != favicon_map.end(); ++iter) 868 favicons->push_back(iter->second); 869} 870 871int IEImporter::CurrentIEVersion() const { 872 static int version = -1; 873 if (version < 0) { 874 wchar_t buffer[128]; 875 DWORD buffer_length = sizeof(buffer); 876 base::win::RegKey reg_key(HKEY_LOCAL_MACHINE, kIEVersionKey, KEY_READ); 877 LONG result = reg_key.ReadValue(L"Version", buffer, &buffer_length, NULL); 878 version = ((result == ERROR_SUCCESS)? _wtoi(buffer) : 0); 879 } 880 return version; 881} 882