1 // Copyright 2013 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/common/file_util.h"
13 #include "base/file_util.h"
14 #include "base/files/file_enumerator.h"
15 #include "base/files/file_path.h"
16 #include "base/files/scoped_temp_dir.h"
17 #include "base/json/json_file_value_serializer.h"
18 #include "base/logging.h"
19 #include "base/memory/scoped_ptr.h"
20 #include "base/strings/stringprintf.h"
21 #include "base/strings/utf_string_conversions.h"
22 #include "base/threading/thread_restrictions.h"
23 #include "extensions/common/constants.h"
24 #include "extensions/common/extension.h"
25 #include "extensions/common/extension_icon_set.h"
26 #include "extensions/common/extension_l10n_util.h"
27 #include "extensions/common/install_warning.h"
28 #include "extensions/common/manifest.h"
29 #include "extensions/common/manifest_constants.h"
30 #include "extensions/common/manifest_handler.h"
31 #include "extensions/common/manifest_handlers/icons_handler.h"
32 #include "extensions/common/message_bundle.h"
33 #include "grit/extensions_strings.h"
34 #include "net/base/escape.h"
35 #include "ui/base/l10n/l10n_util.h"
38 namespace extensions {
42 // Returns true if the given file path exists and is not zero-length.
43 bool ValidateFilePath(const base::FilePath& path) {
45 if (!base::PathExists(path) ||
46 !base::GetFileSize(path, &size) ||
56 const base::FilePath::CharType kTempDirectoryName[] = FILE_PATH_LITERAL("Temp");
58 base::FilePath InstallExtension(const base::FilePath& unpacked_source_dir,
59 const std::string& id,
60 const std::string& version,
61 const base::FilePath& extensions_dir) {
62 base::FilePath extension_dir = extensions_dir.AppendASCII(id);
63 base::FilePath version_dir;
65 // Create the extension directory if it doesn't exist already.
66 if (!base::PathExists(extension_dir)) {
67 if (!base::CreateDirectory(extension_dir))
68 return base::FilePath();
71 // Get a temp directory on the same file system as the profile.
72 base::FilePath install_temp_dir = GetInstallTempDir(extensions_dir);
73 base::ScopedTempDir extension_temp_dir;
74 if (install_temp_dir.empty() ||
75 !extension_temp_dir.CreateUniqueTempDirUnderPath(install_temp_dir)) {
76 LOG(ERROR) << "Creating of temp dir under in the profile failed.";
77 return base::FilePath();
79 base::FilePath crx_temp_source =
80 extension_temp_dir.path().Append(unpacked_source_dir.BaseName());
81 if (!base::Move(unpacked_source_dir, crx_temp_source)) {
82 LOG(ERROR) << "Moving extension from : " << unpacked_source_dir.value()
83 << " to : " << crx_temp_source.value() << " failed.";
84 return base::FilePath();
87 // Try to find a free directory. There can be legitimate conflicts in the case
88 // of overinstallation of the same version.
89 const int kMaxAttempts = 100;
90 for (int i = 0; i < kMaxAttempts; ++i) {
91 base::FilePath candidate = extension_dir.AppendASCII(
92 base::StringPrintf("%s_%u", version.c_str(), i));
93 if (!base::PathExists(candidate)) {
94 version_dir = candidate;
99 if (version_dir.empty()) {
100 LOG(ERROR) << "Could not find a home for extension " << id << " with "
101 << "version " << version << ".";
102 return base::FilePath();
105 if (!base::Move(crx_temp_source, version_dir)) {
106 LOG(ERROR) << "Installing extension from : " << crx_temp_source.value()
107 << " into : " << version_dir.value() << " failed.";
108 return base::FilePath();
114 void UninstallExtension(const base::FilePath& extensions_dir,
115 const std::string& id) {
116 // We don't care about the return value. If this fails (and it can, due to
117 // plugins that aren't unloaded yet), it will get cleaned up by
118 // ExtensionGarbageCollector::GarbageCollectExtensions.
119 base::DeleteFile(extensions_dir.AppendASCII(id), true); // recursive.
122 scoped_refptr<Extension> LoadExtension(const base::FilePath& extension_path,
123 Manifest::Location location,
125 std::string* error) {
126 return LoadExtension(extension_path, std::string(), location, flags, error);
129 scoped_refptr<Extension> LoadExtension(const base::FilePath& extension_path,
130 const std::string& extension_id,
131 Manifest::Location location,
133 std::string* error) {
134 scoped_ptr<base::DictionaryValue> manifest(
135 LoadManifest(extension_path, error));
138 if (!extension_l10n_util::LocalizeExtension(
139 extension_path, manifest.get(), error)) {
143 scoped_refptr<Extension> extension(Extension::Create(
144 extension_path, location, *manifest, flags, extension_id, error));
145 if (!extension.get())
148 std::vector<InstallWarning> warnings;
149 if (!ValidateExtension(extension.get(), error, &warnings))
151 extension->AddInstallWarnings(warnings);
156 base::DictionaryValue* LoadManifest(const base::FilePath& extension_path,
157 std::string* error) {
158 base::FilePath manifest_path = extension_path.Append(kManifestFilename);
159 if (!base::PathExists(manifest_path)) {
160 *error = l10n_util::GetStringUTF8(IDS_EXTENSION_MANIFEST_UNREADABLE);
164 JSONFileValueSerializer serializer(manifest_path);
165 scoped_ptr<base::Value> root(serializer.Deserialize(NULL, error));
167 if (error->empty()) {
168 // If |error| is empty, than the file could not be read.
169 // It would be cleaner to have the JSON reader give a specific error
170 // in this case, but other code tests for a file error with
171 // error->empty(). For now, be consistent.
172 *error = l10n_util::GetStringUTF8(IDS_EXTENSION_MANIFEST_UNREADABLE);
174 *error = base::StringPrintf(
175 "%s %s", manifest_errors::kManifestParseError, error->c_str());
180 if (!root->IsType(base::Value::TYPE_DICTIONARY)) {
181 *error = l10n_util::GetStringUTF8(IDS_EXTENSION_MANIFEST_INVALID);
185 return static_cast<base::DictionaryValue*>(root.release());
188 bool ValidateExtension(const Extension* extension,
190 std::vector<InstallWarning>* warnings) {
191 // Ask registered manifest handlers to validate their paths.
192 if (!ManifestHandler::ValidateExtension(extension, error, warnings))
195 // Check children of extension root to see if any of them start with _ and is
196 // not on the reserved list. We only warn, and do not block the loading of the
199 if (!CheckForIllegalFilenames(extension->path(), &warning))
200 warnings->push_back(InstallWarning(warning));
202 // Check that extensions don't include private key files.
203 std::vector<base::FilePath> private_keys =
204 FindPrivateKeyFiles(extension->path());
205 if (extension->creation_flags() & Extension::ERROR_ON_PRIVATE_KEY) {
206 if (!private_keys.empty()) {
207 // Only print one of the private keys because l10n_util doesn't have a way
208 // to translate a list of strings.
210 l10n_util::GetStringFUTF8(IDS_EXTENSION_CONTAINS_PRIVATE_KEY,
211 private_keys.front().LossyDisplayName());
215 for (size_t i = 0; i < private_keys.size(); ++i) {
216 warnings->push_back(InstallWarning(
217 l10n_util::GetStringFUTF8(IDS_EXTENSION_CONTAINS_PRIVATE_KEY,
218 private_keys[i].LossyDisplayName())));
220 // Only warn; don't block loading the extension.
225 std::vector<base::FilePath> FindPrivateKeyFiles(
226 const base::FilePath& extension_dir) {
227 std::vector<base::FilePath> result;
228 // Pattern matching only works at the root level, so filter manually.
229 base::FileEnumerator traversal(
230 extension_dir, /*recursive=*/true, base::FileEnumerator::FILES);
231 for (base::FilePath current = traversal.Next(); !current.empty();
232 current = traversal.Next()) {
233 if (!current.MatchesExtension(kExtensionKeyFileExtension))
236 std::string key_contents;
237 if (!base::ReadFileToString(current, &key_contents)) {
238 // If we can't read the file, assume it's not a private key.
241 std::string key_bytes;
242 if (!Extension::ParsePEMKeyBytes(key_contents, &key_bytes)) {
243 // If we can't parse the key, assume it's ok too.
247 result.push_back(current);
252 bool CheckForIllegalFilenames(const base::FilePath& extension_path,
253 std::string* error) {
254 // Reserved underscore names.
255 static const base::FilePath::CharType* reserved_names[] = {
256 kLocaleFolder, kPlatformSpecificFolder, FILE_PATH_LITERAL("__MACOSX"), };
257 CR_DEFINE_STATIC_LOCAL(
258 std::set<base::FilePath::StringType>,
259 reserved_underscore_names,
260 (reserved_names, reserved_names + arraysize(reserved_names)));
262 // Enumerate all files and directories in the extension root.
263 // There is a problem when using pattern "_*" with FileEnumerator, so we have
264 // to cheat with find_first_of and match all.
265 const int kFilesAndDirectories =
266 base::FileEnumerator::DIRECTORIES | base::FileEnumerator::FILES;
267 base::FileEnumerator all_files(extension_path, false, kFilesAndDirectories);
270 while (!(file = all_files.Next()).empty()) {
271 base::FilePath::StringType filename = file.BaseName().value();
272 // Skip all that don't start with "_".
273 if (filename.find_first_of(FILE_PATH_LITERAL("_")) != 0)
275 if (reserved_underscore_names.find(filename) ==
276 reserved_underscore_names.end()) {
277 *error = base::StringPrintf(
278 "Cannot load extension with file or directory name %s. "
279 "Filenames starting with \"_\" are reserved for use by the system.",
280 file.BaseName().AsUTF8Unsafe().c_str());
288 base::FilePath GetInstallTempDir(const base::FilePath& extensions_dir) {
289 // We do file IO in this function, but only when the current profile's
290 // Temp directory has never been used before, or in a rare error case.
291 // Developers are not likely to see these situations often, so do an
292 // explicit thread check.
293 base::ThreadRestrictions::AssertIOAllowed();
295 // Create the temp directory as a sub-directory of the Extensions directory.
296 // This guarantees it is on the same file system as the extension's eventual
298 base::FilePath temp_path = extensions_dir.Append(kTempDirectoryName);
299 if (base::PathExists(temp_path)) {
300 if (!base::DirectoryExists(temp_path)) {
301 DLOG(WARNING) << "Not a directory: " << temp_path.value();
302 return base::FilePath();
304 if (!base::PathIsWritable(temp_path)) {
305 DLOG(WARNING) << "Can't write to path: " << temp_path.value();
306 return base::FilePath();
308 // This is a directory we can write to.
312 // Directory doesn't exist, so create it.
313 if (!base::CreateDirectory(temp_path)) {
314 DLOG(WARNING) << "Couldn't create directory: " << temp_path.value();
315 return base::FilePath();
320 void DeleteFile(const base::FilePath& path, bool recursive) {
321 base::DeleteFile(path, recursive);
324 base::FilePath ExtensionURLToRelativeFilePath(const GURL& url) {
325 std::string url_path = url.path();
326 if (url_path.empty() || url_path[0] != '/')
327 return base::FilePath();
329 // Drop the leading slashes and convert %-encoded UTF8 to regular UTF8.
330 std::string file_path = net::UnescapeURLComponent(url_path,
331 net::UnescapeRule::SPACES | net::UnescapeRule::URL_SPECIAL_CHARS);
332 size_t skip = file_path.find_first_not_of("/\\");
333 if (skip != file_path.npos)
334 file_path = file_path.substr(skip);
336 base::FilePath path = base::FilePath::FromUTF8Unsafe(file_path);
338 // It's still possible for someone to construct an annoying URL whose path
339 // would still wind up not being considered relative at this point.
340 // For example: chrome-extension://id/c:////foo.html
341 if (path.IsAbsolute())
342 return base::FilePath();
347 base::FilePath ExtensionResourceURLToFilePath(const GURL& url,
348 const base::FilePath& root) {
349 std::string host = net::UnescapeURLComponent(url.host(),
350 net::UnescapeRule::SPACES | net::UnescapeRule::URL_SPECIAL_CHARS);
352 return base::FilePath();
354 base::FilePath relative_path = ExtensionURLToRelativeFilePath(url);
355 if (relative_path.empty())
356 return base::FilePath();
358 base::FilePath path = root.AppendASCII(host).Append(relative_path);
359 if (!base::PathExists(path))
360 return base::FilePath();
361 path = base::MakeAbsoluteFilePath(path);
362 if (path.empty() || !root.IsParent(path))
363 return base::FilePath();
367 bool ValidateExtensionIconSet(const ExtensionIconSet& icon_set,
368 const Extension* extension,
369 int error_message_id,
370 std::string* error) {
371 for (ExtensionIconSet::IconMap::const_iterator iter = icon_set.map().begin();
372 iter != icon_set.map().end();
374 const base::FilePath path =
375 extension->GetResource(iter->second).GetFilePath();
376 if (!ValidateFilePath(path)) {
377 *error = l10n_util::GetStringFUTF8(error_message_id,
378 base::UTF8ToUTF16(iter->second));
385 MessageBundle* LoadMessageBundle(
386 const base::FilePath& extension_path,
387 const std::string& default_locale,
388 std::string* error) {
390 // Load locale information if available.
391 base::FilePath locale_path = extension_path.Append(kLocaleFolder);
392 if (!base::PathExists(locale_path))
395 std::set<std::string> locales;
396 if (!extension_l10n_util::GetValidLocales(locale_path, &locales, error))
399 if (default_locale.empty() || locales.find(default_locale) == locales.end()) {
400 *error = l10n_util::GetStringUTF8(
401 IDS_EXTENSION_LOCALES_NO_DEFAULT_LOCALE_SPECIFIED);
405 MessageBundle* message_bundle =
406 extension_l10n_util::LoadMessageCatalogs(
409 extension_l10n_util::CurrentLocaleOrDefault(),
413 return message_bundle;
416 std::map<std::string, std::string>* LoadMessageBundleSubstitutionMap(
417 const base::FilePath& extension_path,
418 const std::string& extension_id,
419 const std::string& default_locale) {
420 std::map<std::string, std::string>* return_value =
421 new std::map<std::string, std::string>();
422 if (!default_locale.empty()) {
423 // Touch disk only if extension is localized.
425 scoped_ptr<MessageBundle> bundle(
426 LoadMessageBundle(extension_path, default_locale, &error));
429 *return_value = *bundle->dictionary();
432 // Add @@extension_id reserved message here, so it's available to
433 // non-localized extensions too.
434 return_value->insert(
435 std::make_pair(MessageBundle::kExtensionIdKey, extension_id));
440 base::FilePath GetVerifiedContentsPath(const base::FilePath& extension_path) {
441 return extension_path.Append(kMetadataFolder)
442 .Append(kVerifiedContentsFilename);
444 base::FilePath GetComputedHashesPath(const base::FilePath& extension_path) {
445 return extension_path.Append(kMetadataFolder).Append(kComputedHashesFilename);
448 } // namespace file_util
449 } // namespace extensions