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