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/extensions/unpacker.h"
9 #include "base/file_util.h"
10 #include "base/files/file_enumerator.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/memory/scoped_handle.h"
15 #include "base/numerics/safe_conversions.h"
16 #include "base/strings/string_util.h"
17 #include "base/strings/utf_string_conversions.h"
18 #include "base/threading/thread.h"
19 #include "base/values.h"
20 #include "chrome/common/chrome_utility_messages.h"
21 #include "chrome/common/extensions/api/i18n/default_locale_handler.h"
22 #include "chrome/common/extensions/extension_file_util.h"
23 #include "content/public/child/image_decoder_utils.h"
24 #include "content/public/common/common_param_traits.h"
25 #include "extensions/common/constants.h"
26 #include "extensions/common/extension.h"
27 #include "extensions/common/extension_l10n_util.h"
28 #include "extensions/common/manifest.h"
29 #include "extensions/common/manifest_constants.h"
30 #include "grit/generated_resources.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 "third_party/zlib/google/zip.h"
35 #include "ui/base/l10n/l10n_util.h"
36 #include "ui/gfx/size.h"
38 namespace extensions
{
42 namespace errors
= manifest_errors
;
43 namespace keys
= manifest_keys
;
45 // A limit to stop us passing dangerously large canvases to the browser.
46 const int kMaxImageCanvas
= 4096 * 4096;
48 SkBitmap
DecodeImage(const base::FilePath
& path
) {
49 // Read the file from disk.
50 std::string file_contents
;
51 if (!base::PathExists(path
) ||
52 !base::ReadFileToString(path
, &file_contents
)) {
56 // Decode the image using WebKit's image decoder.
57 const unsigned char* data
=
58 reinterpret_cast<const unsigned char*>(file_contents
.data());
59 SkBitmap bitmap
= content::DecodeImage(data
,
61 file_contents
.length());
62 if (bitmap
.computeSize64() > kMaxImageCanvas
)
67 bool PathContainsParentDirectory(const base::FilePath
& path
) {
68 const base::FilePath::StringType
kSeparators(base::FilePath::kSeparators
);
69 const base::FilePath::StringType
kParentDirectory(
70 base::FilePath::kParentDirectory
);
71 const size_t npos
= base::FilePath::StringType::npos
;
72 const base::FilePath::StringType
& value
= path
.value();
74 for (size_t i
= 0; i
< value
.length(); ) {
75 i
= value
.find(kParentDirectory
, i
);
77 if ((i
== 0 || kSeparators
.find(value
[i
-1]) == npos
) &&
78 (i
+1 < value
.length() || kSeparators
.find(value
[i
+1]) == npos
)) {
88 bool WritePickle(const IPC::Message
& pickle
, const base::FilePath
& dest_path
) {
89 int size
= base::checked_cast
<int>(pickle
.size());
90 const char* data
= static_cast<const char*>(pickle
.data());
91 int bytes_written
= base::WriteFile(dest_path
, data
, size
);
92 return (bytes_written
== size
);
97 struct Unpacker::InternalData
{
98 DecodedImages decoded_images
;
101 Unpacker::Unpacker(const base::FilePath
& extension_path
,
102 const std::string
& extension_id
,
103 Manifest::Location location
,
105 : extension_path_(extension_path
),
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
=
117 temp_install_dir_
.Append(kManifestFilename
);
118 if (!base::PathExists(manifest_path
)) {
119 SetError(errors::kInvalidManifest
);
123 JSONFileValueSerializer
serializer(manifest_path
);
125 scoped_ptr
<base::Value
> root(serializer
.Deserialize(NULL
, &error
));
131 if (!root
->IsType(base::Value::TYPE_DICTIONARY
)) {
132 SetError(errors::kInvalidManifest
);
136 return static_cast<base::DictionaryValue
*>(root
.release());
139 bool Unpacker::ReadAllMessageCatalogs(const std::string
& default_locale
) {
140 base::FilePath locales_path
=
141 temp_install_dir_
.Append(kLocaleFolder
);
143 // Not all folders under _locales have to be valid locales.
144 base::FileEnumerator
locales(locales_path
,
146 base::FileEnumerator::DIRECTORIES
);
148 std::set
<std::string
> all_locales
;
149 extension_l10n_util::GetAllLocales(&all_locales
);
150 base::FilePath locale_path
;
151 while (!(locale_path
= locales
.Next()).empty()) {
152 if (extension_l10n_util::ShouldSkipValidation(locales_path
, locale_path
,
156 base::FilePath messages_path
= locale_path
.Append(kMessagesFilename
);
158 if (!ReadMessageCatalog(messages_path
))
165 bool Unpacker::Run() {
166 DVLOG(1) << "Installing extension " << extension_path_
.value();
168 // <profile>/Extensions/CRX_INSTALL
170 extension_path_
.DirName().AppendASCII(kTempExtensionName
);
172 if (!base::CreateDirectory(temp_install_dir_
)) {
174 l10n_util::GetStringFUTF16(
175 IDS_EXTENSION_PACKAGE_DIRECTORY_ERROR
,
176 base::i18n::GetDisplayStringInLTRDirectionality(
177 temp_install_dir_
.LossyDisplayName())));
181 if (!zip::Unzip(extension_path_
, temp_install_dir_
)) {
182 SetUTF16Error(l10n_util::GetStringUTF16(IDS_EXTENSION_PACKAGE_UNZIP_ERROR
));
186 // Parse the manifest.
187 parsed_manifest_
.reset(ReadManifest());
188 if (!parsed_manifest_
.get())
189 return false; // Error was already reported.
192 scoped_refptr
<Extension
> extension(Extension::Create(
199 if (!extension
.get()) {
204 std::vector
<InstallWarning
> warnings
;
205 if (!extension_file_util::ValidateExtension(extension
.get(),
206 &error
, &warnings
)) {
210 extension
->AddInstallWarnings(warnings
);
212 // Decode any images that the browser needs to display.
213 std::set
<base::FilePath
> image_paths
=
214 extension_file_util::GetBrowserImagePaths(extension
.get());
215 for (std::set
<base::FilePath
>::iterator it
= image_paths
.begin();
216 it
!= image_paths
.end();
218 if (!AddDecodedImage(*it
))
219 return false; // Error was already reported.
222 // Parse all message catalogs (if any).
223 parsed_catalogs_
.reset(new base::DictionaryValue
);
224 if (!LocaleInfo::GetDefaultLocale(extension
.get()).empty()) {
225 if (!ReadAllMessageCatalogs(LocaleInfo::GetDefaultLocale(extension
.get())))
226 return false; // Error was already reported.
232 bool Unpacker::DumpImagesToFile() {
233 IPC::Message pickle
; // We use a Message so we can use WriteParam.
234 IPC::WriteParam(&pickle
, internal_data_
->decoded_images
);
236 base::FilePath path
= extension_path_
.DirName().AppendASCII(
237 kDecodedImagesFilename
);
238 if (!WritePickle(pickle
, path
)) {
239 SetError("Could not write image data to disk.");
246 bool Unpacker::DumpMessageCatalogsToFile() {
248 IPC::WriteParam(&pickle
, *parsed_catalogs_
.get());
250 base::FilePath path
= extension_path_
.DirName().AppendASCII(
251 kDecodedMessageCatalogsFilename
);
252 if (!WritePickle(pickle
, path
)) {
253 SetError("Could not write message catalogs to disk.");
260 bool Unpacker::AddDecodedImage(const base::FilePath
& path
) {
261 // Make sure it's not referencing a file outside the extension's subdir.
262 if (path
.IsAbsolute() || PathContainsParentDirectory(path
)) {
264 l10n_util::GetStringFUTF16(
265 IDS_EXTENSION_PACKAGE_IMAGE_PATH_ERROR
,
266 base::i18n::GetDisplayStringInLTRDirectionality(
267 path
.LossyDisplayName())));
271 SkBitmap image_bitmap
= DecodeImage(temp_install_dir_
.Append(path
));
272 if (image_bitmap
.isNull()) {
274 l10n_util::GetStringFUTF16(
275 IDS_EXTENSION_PACKAGE_IMAGE_ERROR
,
276 base::i18n::GetDisplayStringInLTRDirectionality(
277 path
.BaseName().LossyDisplayName())));
281 internal_data_
->decoded_images
.push_back(MakeTuple(image_bitmap
, path
));
285 bool Unpacker::ReadMessageCatalog(const base::FilePath
& message_path
) {
287 JSONFileValueSerializer
serializer(message_path
);
288 scoped_ptr
<base::DictionaryValue
> root(static_cast<base::DictionaryValue
*>(
289 serializer
.Deserialize(NULL
, &error
)));
291 base::string16 messages_file
= message_path
.LossyDisplayName();
293 // If file is missing, Deserialize will fail with empty error.
294 SetError(base::StringPrintf("%s %s", errors::kLocalesMessagesFileMissing
,
295 base::UTF16ToUTF8(messages_file
).c_str()));
297 SetError(base::StringPrintf("%s: %s",
298 base::UTF16ToUTF8(messages_file
).c_str(),
304 base::FilePath relative_path
;
305 // message_path was created from temp_install_dir. This should never fail.
306 if (!temp_install_dir_
.AppendRelativePath(message_path
, &relative_path
)) {
311 std::string dir_name
= relative_path
.DirName().MaybeAsASCII();
312 if (dir_name
.empty()) {
316 parsed_catalogs_
->Set(dir_name
, root
.release());
321 void Unpacker::SetError(const std::string
&error
) {
322 SetUTF16Error(base::UTF8ToUTF16(error
));
325 void Unpacker::SetUTF16Error(const base::string16
& error
) {
326 error_message_
= error
;
329 } // namespace extensions