Upstream version 7.36.149.0
[platform/framework/web/crosswalk.git] / src / chrome / utility / extensions / unpacker.cc
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 "chrome/utility/extensions/unpacker.h"
6
7 #include <set>
8
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"
38
39 namespace extensions {
40
41 namespace {
42
43 namespace errors = manifest_errors;
44 namespace keys = manifest_keys;
45
46 // A limit to stop us passing dangerously large canvases to the browser.
47 const int kMaxImageCanvas = 4096 * 4096;
48
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)) {
54     return SkBitmap();
55   }
56
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,
61                                          gfx::Size(),
62                                          file_contents.length());
63   if (bitmap.computeSize64() > kMaxImageCanvas)
64     return SkBitmap();
65   return bitmap;
66 }
67
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();
74
75   for (size_t i = 0; i < value.length(); ) {
76     i = value.find(kParentDirectory, i);
77     if (i != npos) {
78       if ((i == 0 || kSeparators.find(value[i-1]) == npos) &&
79           (i+1 < value.length() || kSeparators.find(value[i+1]) == npos)) {
80         return true;
81       }
82       ++i;
83     }
84   }
85
86   return false;
87 }
88
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);
94 }
95
96 }  // namespace
97
98 struct Unpacker::InternalData {
99   DecodedImages decoded_images;
100 };
101
102 Unpacker::Unpacker(const base::FilePath& extension_path,
103                    const std::string& extension_id,
104                    Manifest::Location location,
105                    int creation_flags)
106     : extension_path_(extension_path),
107       extension_id_(extension_id),
108       location_(location),
109       creation_flags_(creation_flags) {
110   internal_data_.reset(new InternalData());
111 }
112
113 Unpacker::~Unpacker() {
114 }
115
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);
121     return NULL;
122   }
123
124   JSONFileValueSerializer serializer(manifest_path);
125   std::string error;
126   scoped_ptr<base::Value> root(serializer.Deserialize(NULL, &error));
127   if (!root.get()) {
128     SetError(error);
129     return NULL;
130   }
131
132   if (!root->IsType(base::Value::TYPE_DICTIONARY)) {
133     SetError(errors::kInvalidManifest);
134     return NULL;
135   }
136
137   return static_cast<base::DictionaryValue*>(root.release());
138 }
139
140 bool Unpacker::ReadAllMessageCatalogs(const std::string& default_locale) {
141   base::FilePath locales_path =
142     temp_install_dir_.Append(kLocaleFolder);
143
144   // Not all folders under _locales have to be valid locales.
145   base::FileEnumerator locales(locales_path,
146                                false,
147                                base::FileEnumerator::DIRECTORIES);
148
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,
154                                                   all_locales))
155       continue;
156
157     base::FilePath messages_path = locale_path.Append(kMessagesFilename);
158
159     if (!ReadMessageCatalog(messages_path))
160       return false;
161   }
162
163   return true;
164 }
165
166 bool Unpacker::Run() {
167   DVLOG(1) << "Installing extension " << extension_path_.value();
168
169   // <profile>/Extensions/CRX_INSTALL
170   temp_install_dir_ =
171       extension_path_.DirName().AppendASCII(kTempExtensionName);
172
173   if (!base::CreateDirectory(temp_install_dir_)) {
174     SetUTF16Error(
175         l10n_util::GetStringFUTF16(
176             IDS_EXTENSION_PACKAGE_DIRECTORY_ERROR,
177             base::i18n::GetDisplayStringInLTRDirectionality(
178                 temp_install_dir_.LossyDisplayName())));
179     return false;
180   }
181
182   if (!zip::Unzip(extension_path_, temp_install_dir_)) {
183     SetUTF16Error(l10n_util::GetStringUTF16(IDS_EXTENSION_PACKAGE_UNZIP_ERROR));
184     return false;
185   }
186
187   // Parse the manifest.
188   parsed_manifest_.reset(ReadManifest());
189   if (!parsed_manifest_.get())
190     return false;  // Error was already reported.
191
192   std::string error;
193   scoped_refptr<Extension> extension(Extension::Create(
194       temp_install_dir_,
195       location_,
196       *parsed_manifest_,
197       creation_flags_,
198       extension_id_,
199       &error));
200   if (!extension.get()) {
201     SetError(error);
202     return false;
203   }
204
205   std::vector<InstallWarning> warnings;
206   if (!file_util::ValidateExtension(extension.get(), &error, &warnings)) {
207     SetError(error);
208     return false;
209   }
210   extension->AddInstallWarnings(warnings);
211
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();
217        ++it) {
218     if (!AddDecodedImage(*it))
219       return false;  // Error was already reported.
220   }
221
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.
227   }
228
229   return true;
230 }
231
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);
235
236   base::FilePath path = extension_path_.DirName().AppendASCII(
237       kDecodedImagesFilename);
238   if (!WritePickle(pickle, path)) {
239     SetError("Could not write image data to disk.");
240     return false;
241   }
242
243   return true;
244 }
245
246 bool Unpacker::DumpMessageCatalogsToFile() {
247   IPC::Message pickle;
248   IPC::WriteParam(&pickle, *parsed_catalogs_.get());
249
250   base::FilePath path = extension_path_.DirName().AppendASCII(
251       kDecodedMessageCatalogsFilename);
252   if (!WritePickle(pickle, path)) {
253     SetError("Could not write message catalogs to disk.");
254     return false;
255   }
256
257   return true;
258 }
259
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)) {
263     SetUTF16Error(
264         l10n_util::GetStringFUTF16(
265             IDS_EXTENSION_PACKAGE_IMAGE_PATH_ERROR,
266             base::i18n::GetDisplayStringInLTRDirectionality(
267                 path.LossyDisplayName())));
268     return false;
269   }
270
271   SkBitmap image_bitmap = DecodeImage(temp_install_dir_.Append(path));
272   if (image_bitmap.isNull()) {
273     SetUTF16Error(
274         l10n_util::GetStringFUTF16(
275             IDS_EXTENSION_PACKAGE_IMAGE_ERROR,
276             base::i18n::GetDisplayStringInLTRDirectionality(
277                 path.BaseName().LossyDisplayName())));
278     return false;
279   }
280
281   internal_data_->decoded_images.push_back(MakeTuple(image_bitmap, path));
282   return true;
283 }
284
285 bool Unpacker::ReadMessageCatalog(const base::FilePath& message_path) {
286   std::string error;
287   JSONFileValueSerializer serializer(message_path);
288   scoped_ptr<base::DictionaryValue> root(static_cast<base::DictionaryValue*>(
289       serializer.Deserialize(NULL, &error)));
290   if (!root.get()) {
291     base::string16 messages_file = message_path.LossyDisplayName();
292     if (error.empty()) {
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()));
296     } else {
297       SetError(base::StringPrintf("%s: %s",
298                                   base::UTF16ToUTF8(messages_file).c_str(),
299                                   error.c_str()));
300     }
301     return false;
302   }
303
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)) {
307     NOTREACHED();
308     return false;
309   }
310
311   std::string dir_name = relative_path.DirName().MaybeAsASCII();
312   if (dir_name.empty()) {
313     NOTREACHED();
314     return false;
315   }
316   parsed_catalogs_->Set(dir_name, root.release());
317
318   return true;
319 }
320
321 void Unpacker::SetError(const std::string &error) {
322   SetUTF16Error(base::UTF8ToUTF16(error));
323 }
324
325 void Unpacker::SetUTF16Error(const base::string16& error) {
326   error_message_ = error;
327 }
328
329 }  // namespace extensions