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 "extensions/utility/unpacker.h"
9 #include "base/files/file_enumerator.h"
10 #include "base/files/file_util.h"
11 #include "base/files/scoped_temp_dir.h"
12 #include "base/i18n/rtl.h"
13 #include "base/json/json_file_value_serializer.h"
14 #include "base/numerics/safe_conversions.h"
15 #include "base/strings/string_util.h"
16 #include "base/strings/utf_string_conversions.h"
17 #include "base/threading/thread.h"
18 #include "base/values.h"
19 #include "content/public/child/image_decoder_utils.h"
20 #include "content/public/common/common_param_traits.h"
21 #include "extensions/common/constants.h"
22 #include "extensions/common/extension.h"
23 #include "extensions/common/extension_l10n_util.h"
24 #include "extensions/common/extension_utility_messages.h"
25 #include "extensions/common/extensions_client.h"
26 #include "extensions/common/file_util.h"
27 #include "extensions/common/manifest.h"
28 #include "extensions/common/manifest_constants.h"
29 #include "extensions/common/manifest_handlers/default_locale_handler.h"
30 #include "extensions/strings/grit/extensions_strings.h"
31 #include "ipc/ipc_message_utils.h"
32 #include "net/base/file_stream.h"
33 #include "third_party/skia/include/core/SkBitmap.h"
34 #include "ui/base/l10n/l10n_util.h"
35 #include "ui/gfx/geometry/size.h"
37 namespace extensions
{
41 namespace errors
= manifest_errors
;
42 namespace keys
= manifest_keys
;
44 // A limit to stop us passing dangerously large canvases to the browser.
45 const int kMaxImageCanvas
= 4096 * 4096;
47 SkBitmap
DecodeImage(const base::FilePath
& path
) {
48 // Read the file from disk.
49 std::string file_contents
;
50 if (!base::PathExists(path
) ||
51 !base::ReadFileToString(path
, &file_contents
)) {
55 // Decode the image using WebKit's image decoder.
56 const unsigned char* data
=
57 reinterpret_cast<const unsigned char*>(file_contents
.data());
59 content::DecodeImage(data
, gfx::Size(), file_contents
.length());
60 if (bitmap
.computeSize64() > kMaxImageCanvas
)
65 bool PathContainsParentDirectory(const base::FilePath
& path
) {
66 const base::FilePath::StringType
kSeparators(base::FilePath::kSeparators
);
67 const base::FilePath::StringType
kParentDirectory(
68 base::FilePath::kParentDirectory
);
69 const size_t npos
= base::FilePath::StringType::npos
;
70 const base::FilePath::StringType
& value
= path
.value();
72 for (size_t i
= 0; i
< value
.length();) {
73 i
= value
.find(kParentDirectory
, i
);
75 if ((i
== 0 || kSeparators
.find(value
[i
- 1]) == npos
) &&
76 (i
+ 1 < value
.length() || kSeparators
.find(value
[i
+ 1]) == npos
)) {
86 bool WritePickle(const IPC::Message
& pickle
, const base::FilePath
& dest_path
) {
87 int size
= base::checked_cast
<int>(pickle
.size());
88 const char* data
= static_cast<const char*>(pickle
.data());
89 int bytes_written
= base::WriteFile(dest_path
, data
, size
);
90 return (bytes_written
== size
);
95 struct Unpacker::InternalData
{
96 DecodedImages decoded_images
;
99 Unpacker::Unpacker(const base::FilePath
& working_dir
,
100 const base::FilePath
& extension_dir
,
101 const std::string
& extension_id
,
102 Manifest::Location location
,
104 : working_dir_(working_dir
),
105 extension_dir_(extension_dir
),
106 extension_id_(extension_id
),
108 creation_flags_(creation_flags
) {
109 internal_data_
.reset(new InternalData());
112 Unpacker::~Unpacker() {
115 base::DictionaryValue
* Unpacker::ReadManifest() {
116 base::FilePath manifest_path
= extension_dir_
.Append(kManifestFilename
);
117 if (!base::PathExists(manifest_path
)) {
118 SetError(errors::kInvalidManifest
);
122 JSONFileValueDeserializer
deserializer(manifest_path
);
124 scoped_ptr
<base::Value
> root(deserializer
.Deserialize(NULL
, &error
));
130 if (!root
->IsType(base::Value::TYPE_DICTIONARY
)) {
131 SetError(errors::kInvalidManifest
);
135 return static_cast<base::DictionaryValue
*>(root
.release());
138 bool Unpacker::ReadAllMessageCatalogs(const std::string
& default_locale
) {
139 base::FilePath locales_path
= extension_dir_
.Append(kLocaleFolder
);
141 // Not all folders under _locales have to be valid locales.
142 base::FileEnumerator
locales(locales_path
, false,
143 base::FileEnumerator::DIRECTORIES
);
145 std::set
<std::string
> all_locales
;
146 extension_l10n_util::GetAllLocales(&all_locales
);
147 base::FilePath locale_path
;
148 while (!(locale_path
= locales
.Next()).empty()) {
149 if (extension_l10n_util::ShouldSkipValidation(locales_path
, locale_path
,
153 base::FilePath messages_path
= locale_path
.Append(kMessagesFilename
);
155 if (!ReadMessageCatalog(messages_path
))
162 bool Unpacker::Run() {
163 // Parse the manifest.
164 parsed_manifest_
.reset(ReadManifest());
165 if (!parsed_manifest_
.get())
166 return false; // Error was already reported.
169 scoped_refptr
<Extension
> extension(
170 Extension::Create(extension_dir_
, location_
, *parsed_manifest_
,
171 creation_flags_
, extension_id_
, &error
));
172 if (!extension
.get()) {
177 std::vector
<InstallWarning
> warnings
;
178 if (!file_util::ValidateExtension(extension
.get(), &error
, &warnings
)) {
182 extension
->AddInstallWarnings(warnings
);
184 // Decode any images that the browser needs to display.
185 std::set
<base::FilePath
> image_paths
=
186 ExtensionsClient::Get()->GetBrowserImagePaths(extension
.get());
187 for (std::set
<base::FilePath
>::iterator it
= image_paths
.begin();
188 it
!= image_paths
.end(); ++it
) {
189 if (!AddDecodedImage(*it
))
190 return false; // Error was already reported.
193 // Parse all message catalogs (if any).
194 parsed_catalogs_
.reset(new base::DictionaryValue
);
195 if (!LocaleInfo::GetDefaultLocale(extension
.get()).empty()) {
196 if (!ReadAllMessageCatalogs(LocaleInfo::GetDefaultLocale(extension
.get())))
197 return false; // Error was already reported.
200 return DumpImagesToFile() && DumpMessageCatalogsToFile();
203 bool Unpacker::DumpImagesToFile() {
204 IPC::Message pickle
; // We use a Message so we can use WriteParam.
205 IPC::WriteParam(&pickle
, internal_data_
->decoded_images
);
207 base::FilePath path
= working_dir_
.AppendASCII(kDecodedImagesFilename
);
208 if (!WritePickle(pickle
, path
)) {
209 SetError("Could not write image data to disk.");
216 bool Unpacker::DumpMessageCatalogsToFile() {
218 IPC::WriteParam(&pickle
, *parsed_catalogs_
.get());
220 base::FilePath path
=
221 working_dir_
.AppendASCII(kDecodedMessageCatalogsFilename
);
222 if (!WritePickle(pickle
, path
)) {
223 SetError("Could not write message catalogs to disk.");
230 bool Unpacker::AddDecodedImage(const base::FilePath
& path
) {
231 // Make sure it's not referencing a file outside the extension's subdir.
232 if (path
.IsAbsolute() || PathContainsParentDirectory(path
)) {
233 SetUTF16Error(l10n_util::GetStringFUTF16(
234 IDS_EXTENSION_PACKAGE_IMAGE_PATH_ERROR
,
235 base::i18n::GetDisplayStringInLTRDirectionality(
236 path
.LossyDisplayName())));
240 SkBitmap image_bitmap
= DecodeImage(extension_dir_
.Append(path
));
241 if (image_bitmap
.isNull()) {
242 SetUTF16Error(l10n_util::GetStringFUTF16(
243 IDS_EXTENSION_PACKAGE_IMAGE_ERROR
,
244 base::i18n::GetDisplayStringInLTRDirectionality(
245 path
.BaseName().LossyDisplayName())));
249 internal_data_
->decoded_images
.push_back(base::MakeTuple(image_bitmap
, path
));
253 bool Unpacker::ReadMessageCatalog(const base::FilePath
& message_path
) {
255 JSONFileValueDeserializer
deserializer(message_path
);
256 scoped_ptr
<base::DictionaryValue
> root(static_cast<base::DictionaryValue
*>(
257 deserializer
.Deserialize(NULL
, &error
)));
259 base::string16 messages_file
= message_path
.LossyDisplayName();
261 // If file is missing, Deserialize will fail with empty error.
262 SetError(base::StringPrintf("%s %s", errors::kLocalesMessagesFileMissing
,
263 base::UTF16ToUTF8(messages_file
).c_str()));
265 SetError(base::StringPrintf(
266 "%s: %s", base::UTF16ToUTF8(messages_file
).c_str(), error
.c_str()));
271 base::FilePath relative_path
;
272 // message_path was created from temp_install_dir. This should never fail.
273 if (!extension_dir_
.AppendRelativePath(message_path
, &relative_path
)) {
278 std::string dir_name
= relative_path
.DirName().MaybeAsASCII();
279 if (dir_name
.empty()) {
283 parsed_catalogs_
->Set(dir_name
, root
.release());
288 void Unpacker::SetError(const std::string
& error
) {
289 SetUTF16Error(base::UTF8ToUTF16(error
));
292 void Unpacker::SetUTF16Error(const base::string16
& error
) {
293 error_message_
= error
;
296 } // namespace extensions