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 "net/base/platform_mime_util.h"
6 
7 #include <string>
8 
9 #include "base/strings/string16.h"
10 #include "base/strings/utf_string_conversions.h"
11 #include "base/win/registry.h"
12 
13 #include <windows.h>
14 
15 namespace net {
16 
GetPlatformMimeTypeFromExtension(const base::FilePath::StringType & ext,std::string * result) const17 bool PlatformMimeUtil::GetPlatformMimeTypeFromExtension(
18     const base::FilePath::StringType& ext, std::string* result) const {
19   // check windows registry for file extension's mime type (registry key
20   // names are not case-sensitive).
21   base::FilePath::StringType value, key = FILE_PATH_LITERAL(".") + ext;
22   base::win::RegKey(HKEY_CLASSES_ROOT, key.c_str(), KEY_READ)
23       .ReadValue(L"Content Type", &value);
24   if (!value.empty()) {
25     *result = base::WideToUTF8(value);
26     return true;
27   }
28   return false;
29 }
30 
GetPlatformPreferredExtensionForMimeType(const std::string & mime_type,base::FilePath::StringType * ext) const31 bool PlatformMimeUtil::GetPlatformPreferredExtensionForMimeType(
32     const std::string& mime_type,
33     base::FilePath::StringType* ext) const {
34   base::FilePath::StringType key =
35       L"MIME\\Database\\Content Type\\" + base::UTF8ToWide(mime_type);
36   if (base::win::RegKey(HKEY_CLASSES_ROOT, key.c_str(), KEY_READ)
37           .ReadValue(L"Extension", ext) != ERROR_SUCCESS) {
38     return false;
39   }
40   // Strip off the leading dot, this should always be the case.
41   if (!ext->empty() && ext->front() == '.')
42     ext->erase(ext->begin());
43 
44   return true;
45 }
46 
GetPlatformExtensionsForMimeType(const std::string & mime_type,std::unordered_set<base::FilePath::StringType> * extensions) const47 void PlatformMimeUtil::GetPlatformExtensionsForMimeType(
48     const std::string& mime_type,
49     std::unordered_set<base::FilePath::StringType>* extensions) const {
50   // Multiple extensions could have the given mime type specified as their types
51   // in their 'HKCR\.<extension>\Content Type' keys. Iterating all the HKCR
52   // entries, though, is wildly impractical. Cheat by returning just the
53   // preferred extension.
54   base::FilePath::StringType ext;
55   if (GetPlatformPreferredExtensionForMimeType(mime_type, &ext))
56     extensions->insert(ext);
57 }
58 
59 }  // namespace net
60