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/file_util.h"
29 #include "extensions/common/manifest.h"
30 #include "extensions/common/manifest_constants.h"
31 #include "grit/generated_resources.h"
32 #include "ipc/ipc_message_utils.h"
33 #include "net/base/file_stream.h"
34 #include "third_party/skia/include/core/SkBitmap.h"
35 #include "third_party/zlib/google/zip.h"
36 #include "ui/base/l10n/l10n_util.h"
37 #include "ui/gfx/size.h"
39 namespace extensions {
43 namespace errors = manifest_errors;
44 namespace keys = manifest_keys;
46 // A limit to stop us passing dangerously large canvases to the browser.
47 const int kMaxImageCanvas = 4096 * 4096;
49 SkBitmap DecodeImage(const base::FilePath& path) {
50 // Read the file from disk.
51 std::string file_contents;
52 if (!base::PathExists(path) ||
53 !base::ReadFileToString(path, &file_contents)) {
57 // Decode the image using WebKit's image decoder.
58 const unsigned char* data =
59 reinterpret_cast<const unsigned char*>(file_contents.data());
60 SkBitmap bitmap = content::DecodeImage(data,
62 file_contents.length());
63 if (bitmap.computeSize64() > kMaxImageCanvas)
68 bool PathContainsParentDirectory(const base::FilePath& path) {
69 const base::FilePath::StringType kSeparators(base::FilePath::kSeparators);
70 const base::FilePath::StringType kParentDirectory(
71 base::FilePath::kParentDirectory);
72 const size_t npos = base::FilePath::StringType::npos;
73 const base::FilePath::StringType& value = path.value();
75 for (size_t i = 0; i < value.length(); ) {
76 i = value.find(kParentDirectory, i);
78 if ((i == 0 || kSeparators.find(value[i-1]) == npos) &&
79 (i+1 < value.length() || kSeparators.find(value[i+1]) == npos)) {
89 bool WritePickle(const IPC::Message& pickle, const base::FilePath& dest_path) {
90 int size = base::checked_cast<int>(pickle.size());
91 const char* data = static_cast<const char*>(pickle.data());
92 int bytes_written = base::WriteFile(dest_path, data, size);
93 return (bytes_written == size);
98 struct Unpacker::InternalData {
99 DecodedImages decoded_images;
102 Unpacker::Unpacker(const base::FilePath& extension_path,
103 const std::string& extension_id,
104 Manifest::Location location,
106 : extension_path_(extension_path),
107 extension_id_(extension_id),
109 creation_flags_(creation_flags) {
110 internal_data_.reset(new InternalData());
113 Unpacker::~Unpacker() {
116 base::DictionaryValue* Unpacker::ReadManifest() {
117 base::FilePath manifest_path =
118 temp_install_dir_.Append(kManifestFilename);
119 if (!base::PathExists(manifest_path)) {
120 SetError(errors::kInvalidManifest);
124 JSONFileValueSerializer serializer(manifest_path);
126 scoped_ptr<base::Value> root(serializer.Deserialize(NULL, &error));
132 if (!root->IsType(base::Value::TYPE_DICTIONARY)) {
133 SetError(errors::kInvalidManifest);
137 return static_cast<base::DictionaryValue*>(root.release());
140 bool Unpacker::ReadAllMessageCatalogs(const std::string& default_locale) {
141 base::FilePath locales_path =
142 temp_install_dir_.Append(kLocaleFolder);
144 // Not all folders under _locales have to be valid locales.
145 base::FileEnumerator locales(locales_path,
147 base::FileEnumerator::DIRECTORIES);
149 std::set<std::string> all_locales;
150 extension_l10n_util::GetAllLocales(&all_locales);
151 base::FilePath locale_path;
152 while (!(locale_path = locales.Next()).empty()) {
153 if (extension_l10n_util::ShouldSkipValidation(locales_path, locale_path,
157 base::FilePath messages_path = locale_path.Append(kMessagesFilename);
159 if (!ReadMessageCatalog(messages_path))
166 bool Unpacker::Run() {
167 DVLOG(1) << "Installing extension " << extension_path_.value();
169 // <profile>/Extensions/CRX_INSTALL
171 extension_path_.DirName().AppendASCII(kTempExtensionName);
173 if (!base::CreateDirectory(temp_install_dir_)) {
175 l10n_util::GetStringFUTF16(
176 IDS_EXTENSION_PACKAGE_DIRECTORY_ERROR,
177 base::i18n::GetDisplayStringInLTRDirectionality(
178 temp_install_dir_.LossyDisplayName())));
182 if (!zip::Unzip(extension_path_, temp_install_dir_)) {
183 SetUTF16Error(l10n_util::GetStringUTF16(IDS_EXTENSION_PACKAGE_UNZIP_ERROR));
187 // Parse the manifest.
188 parsed_manifest_.reset(ReadManifest());
189 if (!parsed_manifest_.get())
190 return false; // Error was already reported.
193 scoped_refptr<Extension> extension(Extension::Create(
200 if (!extension.get()) {
205 std::vector<InstallWarning> warnings;
206 if (!file_util::ValidateExtension(extension.get(), &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