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/utility/importer/ie_importer_win.h"
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/common/url_constants.h"
40 #include "chrome/utility/importer/favicon_reencode.h"
41 #include "components/autofill/core/common/password_form.h"
42 #include "grit/generated_resources.h"
43 #include "ui/base/l10n/l10n_util.h"
48 // Registry key paths from which we import IE settings.
49 const char16 kSearchScopePath[] =
50 L"Software\\Microsoft\\Internet Explorer\\SearchScopes";
51 const char16 kIEVersionKey[] =
52 L"Software\\Microsoft\\Internet Explorer";
53 const char16 kIEToolbarKey[] =
54 L"Software\\Microsoft\\Internet Explorer\\Toolbar";
56 // NTFS stream name of favicon image data.
57 const char16 kFaviconStreamName[] = L":favicon:$DATA";
59 // A struct that hosts the information of AutoComplete data in PStore.
60 struct AutoCompleteInfo {
62 std::vector<string16> data;
66 // Gets the creation time of the given file or directory.
67 base::Time GetFileCreationTime(const 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,
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);
80 // Safely read an object of type T from a raw sequence of bytes.
82 bool BinaryRead(T* data, size_t offset, const std::vector<uint8>& blob) {
83 if (offset + sizeof(T) > blob.size())
85 memcpy(data, &blob[offset], sizeof(T));
89 // Safely read an ITEMIDLIST from a raw sequence of bytes.
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
95 LPCITEMIDLIST BinaryReadItemIDList(size_t offset, size_t idlist_size,
96 const std::vector<uint8>& blob) {
99 // Use a USHORT instead of SHITEMID to avoid buffer over read.
101 if (head >= idlist_size || !BinaryRead(&id_cb, offset + head, blob))
107 return reinterpret_cast<LPCITEMIDLIST>(&blob[offset]);
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).
112 struct 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);
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
134 uint32 rhs_sort_index = (rhs_iter == sort_index_->end() ? kNotSorted
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;
141 return lhs.path.size() < rhs.path.size();
143 const std::map<base::FilePath, uint32>* sort_index_;
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.
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
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;
160 // where each item_id should correspond to a favorites link file (*.url) in
161 // the current folder.
162 bool 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;
170 // Read the number of items.
171 uint32 item_count = 0;
172 if (!BinaryRead(&item_count, kItemCountOffset, blob))
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;
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())
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))
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)))
200 base::FilePath item_relative_path =
201 path.Append(base::FilePath(item_filename).BaseName());
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;
210 bool 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))
227 // Recursively parse subfolders.
228 for (base::win::RegistryKeyIterator child(key.Handle(), L"");
229 child.Valid() && !importer->cancelled();
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,
243 bool 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);
250 return ParseFavoritesOrderRegistryTree(importer, key, base::FilePath(),
254 // Reads the sort order from registry. If failed, we don't touch the list
255 // and use the default (alphabetical) order.
256 void SortBookmarksInIEOrder(
257 const Importer* importer,
258 std::vector<ImportedBookmarkEntry>* bookmarks) {
259 std::map<base::FilePath, uint32> sort_index;
260 if (!ParseFavoritesOrderInfo(importer, &sort_index))
262 IEOrderBookmarkComparator compare = {&sort_index};
263 std::sort(bookmarks->begin(), bookmarks->end(), compare);
266 // Reads an internet shortcut (*.url) |file| and returns a COM object
268 bool LoadInternetShortcut(
269 const 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)))
276 base::win::ScopedComPtr<IPersistFile> persist_file;
277 if (FAILED(persist_file.QueryFrom(url_locator)))
280 // Loads the Internet Shortcut from persistent storage.
281 if (FAILED(persist_file->Load(file.c_str(), STGM_READ)))
284 std::swap(url_locator, *shortcut);
288 // Reads the URL stored in the internet shortcut.
289 GURL 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(WideToUTF16(std::wstring(url)));
296 // Reads the URL of the favicon of the internet shortcut.
297 GURL ReadFaviconURLFromInternetShortcut(IUniformResourceLocator* url_locator) {
298 base::win::ScopedComPtr<IPropertySetStorage> property_set_storage;
299 if (FAILED(property_set_storage.QueryFrom(url_locator)))
302 base::win::ScopedComPtr<IPropertyStorage> property_storage;
303 if (FAILED(property_set_storage->Open(FMTID_Intshcut, STGM_READ,
304 property_storage.Receive()))) {
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
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)
318 return GURL(WideToUTF16(output.get().pwszVal));
321 // Reads the favicon imaga data in an NTFS alternate data stream. This is where
322 // IE7 and above store the data.
323 bool ReadFaviconDataFromInternetShortcut(const string16& file,
325 return base::ReadFileToString(
326 base::FilePath(file + kFaviconStreamName), data);
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.
331 bool ReadFaviconDataFromCache(const GURL& favicon_url, std::string* data) {
332 std::wstring url_wstring(UTF8ToWide(favicon_url.spec()));
334 GetUrlCacheEntryInfoEx(url_wstring.c_str(), NULL, &info_size, NULL, NULL,
336 if (GetLastError() != ERROR_INSUFFICIENT_BUFFER)
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,
346 return base::ReadFileToString(base::FilePath(cache->lpszLocalFileName), data);
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.
352 bool ReadReencodedFaviconData(const 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)) {
361 const unsigned char* ptr =
362 reinterpret_cast<const unsigned char*>(image_data.c_str());
363 return importer::ReencodeFavicon(ptr, image_data.size(), data);
366 // Loads favicon image data and registers to |favicon_map|.
367 void UpdateFaviconMap(
368 const string16& url_file,
370 IUniformResourceLocator* url_locator,
371 std::map<GURL, ImportedFaviconUsage>* favicon_map) {
372 GURL favicon_url = ReadFaviconURLFromInternetShortcut(url_locator);
373 if (!favicon_url.is_valid())
376 std::map<GURL, ImportedFaviconUsage>::iterator it =
377 favicon_map->find(favicon_url);
378 if (it != favicon_map->end()) {
379 // Known favicon URL.
380 it->second.urls.insert(url);
382 // New favicon URL. Read the image data and store.
383 ImportedFaviconUsage usage;
384 if (ReadReencodedFaviconData(url_file, favicon_url, &usage.png_data)) {
385 usage.favicon_url = favicon_url;
386 usage.urls.insert(url);
387 favicon_map->insert(std::make_pair(favicon_url, usage));
395 // {E161255A-37C3-11D2-BCAA-00C04fD929DB}
396 const GUID IEImporter::kPStoreAutocompleteGUID = {
397 0xe161255a, 0x37c3, 0x11d2,
398 { 0xbc, 0xaa, 0x00, 0xc0, 0x4f, 0xd9, 0x29, 0xdb }
400 // {A79029D6-753E-4e27-B807-3D46AB1545DF}
401 const GUID IEImporter::kUnittestGUID = {
402 0xa79029d6, 0x753e, 0x4e27,
403 { 0xb8, 0x7, 0x3d, 0x46, 0xab, 0x15, 0x45, 0xdf }
406 IEImporter::IEImporter() {
409 void IEImporter::StartImport(const importer::SourceProfile& source_profile,
411 ImporterBridge* bridge) {
413 source_path_ = source_profile.source_path;
415 bridge_->NotifyStarted();
417 if ((items & importer::HOME_PAGE) && !cancelled()) {
418 bridge_->NotifyItemStarted(importer::HOME_PAGE);
419 ImportHomepage(); // Doesn't have a UI item.
420 bridge_->NotifyItemEnded(importer::HOME_PAGE);
422 // The order here is important!
423 if ((items & importer::HISTORY) && !cancelled()) {
424 bridge_->NotifyItemStarted(importer::HISTORY);
426 bridge_->NotifyItemEnded(importer::HISTORY);
428 if ((items & importer::FAVORITES) && !cancelled()) {
429 bridge_->NotifyItemStarted(importer::FAVORITES);
431 bridge_->NotifyItemEnded(importer::FAVORITES);
433 if ((items & importer::SEARCH_ENGINES) && !cancelled()) {
434 bridge_->NotifyItemStarted(importer::SEARCH_ENGINES);
435 ImportSearchEngines();
436 bridge_->NotifyItemEnded(importer::SEARCH_ENGINES);
438 if ((items & importer::PASSWORDS) && !cancelled()) {
439 bridge_->NotifyItemStarted(importer::PASSWORDS);
440 // Always import IE6 passwords.
441 ImportPasswordsIE6();
443 if (CurrentIEVersion() >= 7)
444 ImportPasswordsIE7();
445 bridge_->NotifyItemEnded(importer::PASSWORDS);
447 bridge_->NotifyEnded();
450 IEImporter::~IEImporter() {
453 void IEImporter::ImportFavorites() {
455 if (!GetFavoritesInfo(&info))
458 BookmarkVector bookmarks;
459 std::vector<ImportedFaviconUsage> favicons;
460 ParseFavoritesFolder(info, &bookmarks, &favicons);
462 if (!bookmarks.empty() && !cancelled()) {
463 const string16& first_folder_name =
464 l10n_util::GetStringUTF16(IDS_BOOKMARK_GROUP_FROM_IE);
465 bridge_->AddBookmarks(bookmarks, first_folder_name);
467 if (!favicons.empty() && !cancelled())
468 bridge_->SetFavicons(favicons);
471 void IEImporter::ImportHistory() {
472 const std::string kSchemes[] = {content::kHttpScheme,
473 content::kHttpsScheme,
475 chrome::kFileScheme};
476 int total_schemes = arraysize(kSchemes);
478 base::win::ScopedComPtr<IUrlHistoryStg2> url_history_stg2;
480 result = url_history_stg2.CreateInstance(CLSID_CUrlHistory, NULL,
481 CLSCTX_INPROC_SERVER);
484 base::win::ScopedComPtr<IEnumSTATURL> enum_url;
485 if (SUCCEEDED(result = url_history_stg2->EnumUrls(enum_url.Receive()))) {
486 std::vector<ImporterURLRow> rows;
489 while (!cancelled() &&
490 (result = enum_url->Next(1, &stat_url, &fetched)) == S_OK) {
492 if (stat_url.pwcsUrl) {
493 url_string = stat_url.pwcsUrl;
494 CoTaskMemFree(stat_url.pwcsUrl);
496 string16 title_string;
497 if (stat_url.pwcsTitle) {
498 title_string = stat_url.pwcsTitle;
499 CoTaskMemFree(stat_url.pwcsTitle);
502 GURL url(url_string);
503 // Skips the URLs that are invalid or have other schemes.
504 if (!url.is_valid() ||
505 (std::find(kSchemes, kSchemes + total_schemes, url.scheme()) ==
506 kSchemes + total_schemes))
509 ImporterURLRow row(url);
510 row.title = title_string;
511 row.last_visit = base::Time::FromFileTime(stat_url.ftLastVisited);
512 if (stat_url.dwFlags == STATURL_QUERYFLAG_TOPLEVEL) {
522 if (!rows.empty() && !cancelled()) {
523 bridge_->SetHistoryItems(rows, importer::VISIT_SOURCE_IE_IMPORTED);
528 void IEImporter::ImportPasswordsIE6() {
529 GUID AutocompleteGUID = kPStoreAutocompleteGUID;
530 if (!source_path_.empty()) {
531 // We supply a fake GUID for testting.
532 AutocompleteGUID = kUnittestGUID;
535 // The PStoreCreateInstance function retrieves an interface pointer
536 // to a storage provider. But this function has no associated import
537 // library or header file, we must call it using the LoadLibrary()
538 // and GetProcAddress() functions.
539 typedef HRESULT (WINAPI *PStoreCreateFunc)(IPStore**, DWORD, DWORD, DWORD);
540 HMODULE pstorec_dll = LoadLibrary(L"pstorec.dll");
543 PStoreCreateFunc PStoreCreateInstance =
544 (PStoreCreateFunc)GetProcAddress(pstorec_dll, "PStoreCreateInstance");
545 if (!PStoreCreateInstance) {
546 FreeLibrary(pstorec_dll);
550 base::win::ScopedComPtr<IPStore, &IID_IPStore> pstore;
551 HRESULT result = PStoreCreateInstance(pstore.Receive(), 0, 0, 0);
552 if (result != S_OK) {
553 FreeLibrary(pstorec_dll);
557 std::vector<AutoCompleteInfo> ac_list;
559 // Enumerates AutoComplete items in the protected database.
560 base::win::ScopedComPtr<IEnumPStoreItems, &IID_IEnumPStoreItems> item;
561 result = pstore->EnumItems(0, &AutocompleteGUID,
562 &AutocompleteGUID, 0, item.Receive());
563 if (result != PST_E_OK) {
565 FreeLibrary(pstorec_dll);
570 while (!cancelled() && SUCCEEDED(item->Next(1, &item_name, 0))) {
572 unsigned char* buffer = NULL;
573 result = pstore->ReadItem(0, &AutocompleteGUID, &AutocompleteGUID,
574 item_name, &length, &buffer, NULL, 0);
575 if (SUCCEEDED(result)) {
579 data.insert(0, reinterpret_cast<wchar_t*>(buffer),
580 length / sizeof(wchar_t));
582 // The key name is always ended with ":StringData".
583 const wchar_t kDataSuffix[] = L":StringData";
584 size_t i = ac.key.rfind(kDataSuffix);
585 if (i != string16::npos && ac.key.substr(i) == kDataSuffix) {
587 ac.is_url = (ac.key.find(L"://") != string16::npos);
588 ac_list.push_back(ac);
589 base::SplitString(data, L'\0', &ac_list[ac_list.size() - 1].data);
591 CoTaskMemFree(buffer);
593 CoTaskMemFree(item_name);
595 // Releases them before unload the dll.
598 FreeLibrary(pstorec_dll);
601 for (i = 0; i < ac_list.size(); i++) {
602 if (!ac_list[i].is_url || ac_list[i].data.size() < 2)
605 GURL url(ac_list[i].key.c_str());
606 if (!(LowerCaseEqualsASCII(url.scheme(), content::kHttpScheme) ||
607 LowerCaseEqualsASCII(url.scheme(), content::kHttpsScheme))) {
611 autofill::PasswordForm form;
612 GURL::Replacements rp;
617 form.origin = url.ReplaceComponents(rp);
618 form.username_value = ac_list[i].data[0];
619 form.password_value = ac_list[i].data[1];
620 form.signon_realm = url.GetOrigin().spec();
622 // This is not precise, because a scheme of https does not imply a valid
623 // certificate was presented; however we assign it this way so that if we
624 // import a password from IE whose scheme is https, we give it the benefit
625 // of the doubt and DONT auto-fill it unless the form appears under
626 // valid SSL conditions.
627 form.ssl_valid = url.SchemeIsSecure();
629 // Goes through the list to find out the username field
631 size_t list_it, item_it;
632 for (list_it = 0; list_it < ac_list.size(); ++list_it) {
633 if (ac_list[list_it].is_url)
636 for (item_it = 0; item_it < ac_list[list_it].data.size(); ++item_it)
637 if (ac_list[list_it].data[item_it] == form.username_value) {
638 form.username_element = ac_list[list_it].key;
643 bridge_->SetPasswordForm(form);
647 void IEImporter::ImportPasswordsIE7() {
648 base::string16 key_path(importer::GetIE7PasswordsKey());
649 base::win::RegKey key(HKEY_CURRENT_USER, key_path.c_str(), KEY_READ);
650 base::win::RegistryValueIterator reg_iterator(HKEY_CURRENT_USER,
652 importer::ImporterIE7PasswordInfo password_info;
653 while (reg_iterator.Valid() && !cancelled()) {
654 // Get the size of the encrypted data.
656 key.ReadValue(reg_iterator.Name(), NULL, &value_len, NULL);
658 // Query the encrypted data.
659 password_info.encrypted_data.resize(value_len);
660 if (key.ReadValue(reg_iterator.Name(),
661 &password_info.encrypted_data.front(),
662 &value_len, NULL) == ERROR_SUCCESS) {
663 password_info.url_hash = reg_iterator.Name();
664 password_info.date_created = base::Time::Now();
666 bridge_->AddIE7PasswordInfo(password_info);
674 void IEImporter::ImportSearchEngines() {
675 // On IE, search engines are stored in the registry, under:
676 // Software\Microsoft\Internet Explorer\SearchScopes
677 // Each key represents a search engine. The URL value contains the URL and
678 // the DisplayName the name.
679 typedef std::map<std::string, string16> SearchEnginesMap;
680 SearchEnginesMap search_engines_map;
681 for (base::win::RegistryKeyIterator key_iter(HKEY_CURRENT_USER,
682 kSearchScopePath); key_iter.Valid(); ++key_iter) {
683 string16 sub_key_name = kSearchScopePath;
684 sub_key_name.append(L"\\").append(key_iter.Name());
685 base::win::RegKey sub_key(HKEY_CURRENT_USER, sub_key_name.c_str(),
688 if ((sub_key.ReadValue(L"URL", &wide_url) != ERROR_SUCCESS) ||
690 VLOG(1) << "No URL for IE search engine at " << key_iter.Name();
693 // For the name, we try the default value first (as Live Search uses a
694 // non displayable name in DisplayName, and the readable name under the
697 if ((sub_key.ReadValue(NULL, &name) != ERROR_SUCCESS) || name.empty()) {
698 // Try the displayable name.
699 if ((sub_key.ReadValue(L"DisplayName", &name) != ERROR_SUCCESS) ||
701 VLOG(1) << "No name for IE search engine at " << key_iter.Name();
706 std::string url(WideToUTF8(wide_url));
707 SearchEnginesMap::iterator t_iter = search_engines_map.find(url);
708 if (t_iter == search_engines_map.end()) {
709 // First time we see that URL.
711 if (gurl.is_valid()) {
712 t_iter = search_engines_map.insert(std::make_pair(url, name)).first;
716 // ProfileWriter::AddKeywords() requires a vector and we have a map.
717 std::vector<importer::URLKeywordInfo> url_keywords;
718 for (SearchEnginesMap::iterator i = search_engines_map.begin();
719 i != search_engines_map.end(); ++i) {
720 importer::URLKeywordInfo url_keyword_info;
721 url_keyword_info.url = GURL(i->first);
722 url_keyword_info.display_name = i->second;
723 url_keywords.push_back(url_keyword_info);
725 bridge_->SetKeywords(url_keywords, true);
728 void IEImporter::ImportHomepage() {
729 const wchar_t* kIEHomepage = L"Start Page";
730 const wchar_t* kIEDefaultHomepage = L"Default_Page_URL";
732 base::string16 key_path(importer::GetIESettingsKey());
734 base::win::RegKey key(HKEY_CURRENT_USER, key_path.c_str(), KEY_READ);
735 string16 homepage_url;
736 if (key.ReadValue(kIEHomepage, &homepage_url) != ERROR_SUCCESS ||
737 homepage_url.empty())
740 GURL homepage = GURL(homepage_url);
741 if (!homepage.is_valid())
744 // Check to see if this is the default website and skip import.
745 base::win::RegKey keyDefault(HKEY_LOCAL_MACHINE, key_path.c_str(), KEY_READ);
746 string16 default_homepage_url;
747 LONG result = keyDefault.ReadValue(kIEDefaultHomepage, &default_homepage_url);
748 if (result == ERROR_SUCCESS && !default_homepage_url.empty()) {
749 if (homepage.spec() == GURL(default_homepage_url).spec())
752 bridge_->AddHomePage(homepage);
755 bool IEImporter::GetFavoritesInfo(IEImporter::FavoritesInfo* info) {
756 if (!source_path_.empty()) {
757 // Source path exists during testing.
758 info->path = source_path_;
759 info->path = info->path.AppendASCII("Favorites");
760 info->links_folder = L"Links";
764 // IE stores the favorites in the Favorites under user profile's folder.
765 wchar_t buffer[MAX_PATH];
766 if (FAILED(SHGetFolderPath(NULL, CSIDL_FAVORITES, NULL,
767 SHGFP_TYPE_CURRENT, buffer)))
769 info->path = base::FilePath(buffer);
771 // There is a Links folder under Favorites folder in Windows Vista, but it
772 // is not recording in Vista's registry. So in Vista, we assume the Links
773 // folder is under Favorites folder since it looks like there is not name
774 // different in every language version of Windows Vista.
775 if (base::win::GetVersion() < base::win::VERSION_VISTA) {
776 // The Link folder name is stored in the registry.
777 DWORD buffer_length = sizeof(buffer);
778 base::win::RegKey reg_key(HKEY_CURRENT_USER, kIEToolbarKey, KEY_READ);
779 if (reg_key.ReadValue(L"LinksFolderName", buffer,
780 &buffer_length, NULL) != ERROR_SUCCESS)
782 info->links_folder = buffer;
784 info->links_folder = L"Links";
790 void IEImporter::ParseFavoritesFolder(
791 const FavoritesInfo& info,
792 BookmarkVector* bookmarks,
793 std::vector<ImportedFaviconUsage>* favicons) {
795 std::vector<base::FilePath::StringType> file_list;
796 base::FilePath favorites_path(info.path);
797 // Favorites path length. Make sure it doesn't include the trailing \.
798 size_t favorites_path_len =
799 favorites_path.StripTrailingSeparators().value().size();
800 base::FileEnumerator file_enumerator(
801 favorites_path, true, base::FileEnumerator::FILES);
802 while (!(file = file_enumerator.Next()).value().empty() && !cancelled())
803 file_list.push_back(file.value());
805 // Keep the bookmarks in alphabetical order.
806 std::sort(file_list.begin(), file_list.end());
808 // Map from favicon URLs to the favicon data (the binary image data and the
809 // set of bookmark URLs referring to the favicon).
810 typedef std::map<GURL, ImportedFaviconUsage> FaviconMap;
811 FaviconMap favicon_map;
813 for (std::vector<base::FilePath::StringType>::iterator it = file_list.begin();
814 it != file_list.end(); ++it) {
815 base::FilePath shortcut(*it);
816 if (!LowerCaseEqualsASCII(shortcut.Extension(), ".url"))
819 // Skip the bookmark with invalid URL.
820 base::win::ScopedComPtr<IUniformResourceLocator> url_locator;
821 if (!LoadInternetShortcut(*it, &url_locator))
823 GURL url = ReadURLFromInternetShortcut(url_locator);
826 // Skip default bookmarks. go.microsoft.com redirects to
827 // search.microsoft.com, and http://go.microsoft.com/fwlink/?LinkId=XXX,
828 // which URLs IE has as default, to some another sites.
829 // We expect that users will never themselves create bookmarks having this
831 if (url.host() == "go.microsoft.com")
834 UpdateFaviconMap(*it, url, url_locator, &favicon_map);
836 // Make the relative path from the Favorites folder, without the basename.
837 // ex. Suppose that the Favorites folder is C:\Users\Foo\Favorites.
838 // C:\Users\Foo\Favorites\Foo.url -> ""
839 // C:\Users\Foo\Favorites\Links\Bar\Baz.url -> "Links\Bar"
840 base::FilePath::StringType relative_string =
841 shortcut.DirName().value().substr(favorites_path_len);
842 if (!relative_string.empty() &&
843 base::FilePath::IsSeparator(relative_string[0]))
844 relative_string = relative_string.substr(1);
845 base::FilePath relative_path(relative_string);
847 ImportedBookmarkEntry entry;
848 // Remove the dot, the file extension, and the directory path.
849 entry.title = shortcut.RemoveExtension().BaseName().value();
851 entry.creation_time = GetFileCreationTime(*it);
852 if (!relative_path.empty())
853 relative_path.GetComponents(&entry.path);
856 if (!entry.path.empty() && entry.path[0] == info.links_folder) {
857 // Bookmarks in the Link folder should be imported to the toolbar.
858 entry.in_toolbar = true;
860 bookmarks->push_back(entry);
863 // Reflect the menu order in IE.
864 SortBookmarksInIEOrder(this, bookmarks);
866 // Record favicon data.
867 for (FaviconMap::iterator iter = favicon_map.begin();
868 iter != favicon_map.end(); ++iter)
869 favicons->push_back(iter->second);
872 int IEImporter::CurrentIEVersion() const {
873 static int version = -1;
876 DWORD buffer_length = sizeof(buffer);
877 base::win::RegKey reg_key(HKEY_LOCAL_MACHINE, kIEVersionKey, KEY_READ);
878 LONG result = reg_key.ReadValue(L"Version", buffer, &buffer_length, NULL);
879 version = ((result == ERROR_SUCCESS)? _wtoi(buffer) : 0);