external_provider_impl.cc revision 4e180b6a0b4720a9b8e9e959a882386f690f08ff
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/browser/extensions/external_provider_impl.h"
6
7#include <set>
8#include <vector>
9
10#include "base/command_line.h"
11#include "base/files/file_path.h"
12#include "base/logging.h"
13#include "base/memory/linked_ptr.h"
14#include "base/metrics/field_trial.h"
15#include "base/path_service.h"
16#include "base/strings/string_util.h"
17#include "base/values.h"
18#include "base/version.h"
19#include "chrome/browser/app_mode/app_mode_utils.h"
20#include "chrome/browser/browser_process.h"
21#include "chrome/browser/extensions/extension_service.h"
22#include "chrome/browser/extensions/extension_system.h"
23#include "chrome/browser/extensions/external_component_loader.h"
24#include "chrome/browser/extensions/external_policy_loader.h"
25#include "chrome/browser/extensions/external_pref_loader.h"
26#include "chrome/browser/extensions/external_provider_interface.h"
27#include "chrome/browser/profiles/profile.h"
28#include "chrome/common/chrome_paths.h"
29#include "chrome/common/chrome_switches.h"
30#include "chrome/common/extensions/extension.h"
31#include "chrome/common/pref_names.h"
32#include "content/public/browser/browser_thread.h"
33#include "extensions/common/manifest.h"
34#include "ui/base/l10n/l10n_util.h"
35
36#if defined(OS_CHROMEOS)
37#include "chrome/browser/chromeos/extensions/external_pref_cache_loader.h"
38#include "chrome/browser/chromeos/login/user_manager.h"
39#include "chrome/browser/chromeos/policy/app_pack_updater.h"
40#include "chrome/browser/policy/browser_policy_connector.h"
41#else
42#include "chrome/browser/extensions/default_apps.h"
43#endif
44
45#if defined(OS_WIN)
46#include "chrome/browser/extensions/external_registry_loader_win.h"
47#endif
48
49using content::BrowserThread;
50
51namespace extensions {
52
53// Constants for keeping track of extension preferences in a dictionary.
54const char ExternalProviderImpl::kExternalCrx[] = "external_crx";
55const char ExternalProviderImpl::kExternalVersion[] = "external_version";
56const char ExternalProviderImpl::kExternalUpdateUrl[] = "external_update_url";
57const char ExternalProviderImpl::kSupportedLocales[] = "supported_locales";
58const char ExternalProviderImpl::kIsBookmarkApp[] = "is_bookmark_app";
59const char ExternalProviderImpl::kIsFromWebstore[] = "is_from_webstore";
60const char ExternalProviderImpl::kKeepIfPresent[] = "keep_if_present";
61const char ExternalProviderImpl::kRequirePermissionsConsent[] =
62    "require_permissions_consent";
63
64ExternalProviderImpl::ExternalProviderImpl(VisitorInterface* service,
65                                           ExternalLoader* loader,
66                                           Profile* profile,
67                                           Manifest::Location crx_location,
68                                           Manifest::Location download_location,
69                                           int creation_flags)
70    : crx_location_(crx_location),
71      download_location_(download_location),
72      service_(service),
73      ready_(false),
74      loader_(loader),
75      profile_(profile),
76      creation_flags_(creation_flags),
77      auto_acknowledge_(false) {
78  loader_->Init(this);
79}
80
81ExternalProviderImpl::~ExternalProviderImpl() {
82  CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
83  loader_->OwnerShutdown();
84}
85
86void ExternalProviderImpl::VisitRegisteredExtension() {
87  // The loader will call back to SetPrefs.
88  loader_->StartLoading();
89}
90
91void ExternalProviderImpl::SetPrefs(base::DictionaryValue* prefs) {
92  CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
93
94  // Check if the service is still alive. It is possible that it went
95  // away while |loader_| was working on the FILE thread.
96  if (!service_) return;
97
98  prefs_.reset(prefs);
99  ready_ = true;  // Queries for extensions are allowed from this point.
100
101  // Set of unsupported extensions that need to be deleted from prefs_.
102  std::set<std::string> unsupported_extensions;
103
104  // Notify ExtensionService about all the extensions this provider has.
105  for (base::DictionaryValue::Iterator i(*prefs_); !i.IsAtEnd(); i.Advance()) {
106    const std::string& extension_id = i.key();
107    const base::DictionaryValue* extension = NULL;
108
109    if (!Extension::IdIsValid(extension_id)) {
110      LOG(WARNING) << "Malformed extension dictionary: key "
111                   << extension_id.c_str() << " is not a valid id.";
112      continue;
113    }
114
115    if (!i.value().GetAsDictionary(&extension)) {
116      LOG(WARNING) << "Malformed extension dictionary: key "
117                   << extension_id.c_str()
118                   << " has a value that is not a dictionary.";
119      continue;
120    }
121
122    base::FilePath::StringType external_crx;
123    const Value* external_version_value = NULL;
124    std::string external_version;
125    std::string external_update_url;
126
127    bool has_external_crx = extension->GetString(kExternalCrx, &external_crx);
128
129    bool has_external_version = false;
130    if (extension->Get(kExternalVersion, &external_version_value)) {
131      if (external_version_value->IsType(Value::TYPE_STRING)) {
132        external_version_value->GetAsString(&external_version);
133        has_external_version = true;
134      } else {
135        LOG(WARNING) << "Malformed extension dictionary for extension: "
136                     << extension_id.c_str() << ". " << kExternalVersion
137                     << " value must be a string.";
138        continue;
139      }
140    }
141
142    bool has_external_update_url = extension->GetString(kExternalUpdateUrl,
143                                                        &external_update_url);
144    if (has_external_crx != has_external_version) {
145      LOG(WARNING) << "Malformed extension dictionary for extension: "
146                   << extension_id.c_str() << ".  " << kExternalCrx
147                   << " and " << kExternalVersion << " must be used together.";
148      continue;
149    }
150
151    if (has_external_crx == has_external_update_url) {
152      LOG(WARNING) << "Malformed extension dictionary for extension: "
153                   << extension_id.c_str() << ".  Exactly one of the "
154                   << "followng keys should be used: " << kExternalCrx
155                   << ", " << kExternalUpdateUrl << ".";
156      continue;
157    }
158
159    // Check that extension supports current browser locale.
160    const base::ListValue* supported_locales = NULL;
161    if (extension->GetList(kSupportedLocales, &supported_locales)) {
162      std::vector<std::string> browser_locales;
163      l10n_util::GetParentLocales(g_browser_process->GetApplicationLocale(),
164                                  &browser_locales);
165
166      size_t num_locales = supported_locales->GetSize();
167      bool locale_supported = false;
168      for (size_t j = 0; j < num_locales; j++) {
169        std::string current_locale;
170        if (supported_locales->GetString(j, &current_locale) &&
171            l10n_util::IsValidLocaleSyntax(current_locale)) {
172          current_locale = l10n_util::NormalizeLocale(current_locale);
173          if (std::find(browser_locales.begin(), browser_locales.end(),
174                        current_locale) != browser_locales.end()) {
175            locale_supported = true;
176            break;
177          }
178        } else {
179          LOG(WARNING) << "Unrecognized locale '" << current_locale
180                       << "' found as supported locale for extension: "
181                       << extension_id;
182        }
183      }
184
185      if (!locale_supported) {
186        unsupported_extensions.insert(extension_id);
187        VLOG(1) << "Skip installing (or uninstall) external extension: "
188                << extension_id << " because the extension doesn't support "
189                << "the browser locale.";
190        continue;
191      }
192    }
193
194    int creation_flags = creation_flags_;
195    bool is_bookmark_app;
196    if (extension->GetBoolean(kIsBookmarkApp, &is_bookmark_app) &&
197        is_bookmark_app) {
198      creation_flags |= Extension::FROM_BOOKMARK;
199    }
200    bool is_from_webstore;
201    if (extension->GetBoolean(kIsFromWebstore, &is_from_webstore) &&
202        is_from_webstore) {
203      creation_flags |= Extension::FROM_WEBSTORE;
204    }
205    bool keep_if_present;
206    if (extension->GetBoolean(kKeepIfPresent, &keep_if_present) &&
207        keep_if_present && profile_) {
208      ExtensionServiceInterface* extension_service =
209          ExtensionSystem::Get(profile_)->extension_service();
210      const Extension* extension = extension_service ?
211          extension_service->GetExtensionById(extension_id, true) : NULL;
212      if (!extension) {
213        VLOG(1) << "Skip installing (or uninstall) external extension: "
214                << extension_id << " because the extension should be kept "
215                << "only if it is already installed.";
216        continue;
217      }
218    }
219    bool require_permissions_consent;
220    if (extension->GetBoolean(kRequirePermissionsConsent,
221                              &require_permissions_consent) &&
222        require_permissions_consent) {
223      creation_flags |= Extension::REQUIRE_PERMISSIONS_CONSENT;
224    }
225
226    if (has_external_crx) {
227      if (crx_location_ == Manifest::INVALID_LOCATION) {
228        LOG(WARNING) << "This provider does not support installing external "
229                     << "extensions from crx files.";
230        continue;
231      }
232      if (external_crx.find(base::FilePath::kParentDirectory) !=
233          base::StringPiece::npos) {
234        LOG(WARNING) << "Path traversal not allowed in path: "
235                     << external_crx.c_str();
236        continue;
237      }
238
239      // If the path is relative, and the provider has a base path,
240      // build the absolute path to the crx file.
241      base::FilePath path(external_crx);
242      if (!path.IsAbsolute()) {
243        base::FilePath base_path = loader_->GetBaseCrxFilePath();
244        if (base_path.empty()) {
245          LOG(WARNING) << "File path " << external_crx.c_str()
246                       << " is relative.  An absolute path is required.";
247          continue;
248        }
249        path = base_path.Append(external_crx);
250      }
251
252      Version version(external_version);
253      if (!version.IsValid()) {
254        LOG(WARNING) << "Malformed extension dictionary for extension: "
255                     << extension_id.c_str() << ".  Invalid version string \""
256                     << external_version << "\".";
257        continue;
258      }
259      service_->OnExternalExtensionFileFound(extension_id, &version, path,
260                                             crx_location_, creation_flags,
261                                             auto_acknowledge_);
262    } else {  // if (has_external_update_url)
263      CHECK(has_external_update_url);  // Checking of keys above ensures this.
264      if (download_location_ == Manifest::INVALID_LOCATION) {
265        LOG(WARNING) << "This provider does not support installing external "
266                     << "extensions from update URLs.";
267        continue;
268      }
269      GURL update_url(external_update_url);
270      if (!update_url.is_valid()) {
271        LOG(WARNING) << "Malformed extension dictionary for extension: "
272                     << extension_id.c_str() << ".  Key " << kExternalUpdateUrl
273                     << " has value \"" << external_update_url
274                     << "\", which is not a valid URL.";
275        continue;
276      }
277      service_->OnExternalExtensionUpdateUrlFound(
278          extension_id, update_url, download_location_, creation_flags,
279          auto_acknowledge_);
280    }
281  }
282
283  for (std::set<std::string>::iterator it = unsupported_extensions.begin();
284       it != unsupported_extensions.end(); ++it) {
285    // Remove extension for the list of know external extensions. The extension
286    // will be uninstalled later because provider doesn't provide it anymore.
287    prefs_->Remove(*it, NULL);
288  }
289
290  service_->OnExternalProviderReady(this);
291}
292
293void ExternalProviderImpl::ServiceShutdown() {
294  service_ = NULL;
295}
296
297bool ExternalProviderImpl::IsReady() const {
298  return ready_;
299}
300
301bool ExternalProviderImpl::HasExtension(
302    const std::string& id) const {
303  CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
304  CHECK(prefs_.get());
305  CHECK(ready_);
306  return prefs_->HasKey(id);
307}
308
309bool ExternalProviderImpl::GetExtensionDetails(
310    const std::string& id, Manifest::Location* location,
311    scoped_ptr<Version>* version) const {
312  CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
313  CHECK(prefs_.get());
314  CHECK(ready_);
315  base::DictionaryValue* extension = NULL;
316  if (!prefs_->GetDictionary(id, &extension))
317    return false;
318
319  Manifest::Location loc = Manifest::INVALID_LOCATION;
320  if (extension->HasKey(kExternalUpdateUrl)) {
321    loc = download_location_;
322
323  } else if (extension->HasKey(kExternalCrx)) {
324    loc = crx_location_;
325
326    std::string external_version;
327    if (!extension->GetString(kExternalVersion, &external_version))
328      return false;
329
330    if (version)
331      version->reset(new Version(external_version));
332
333  } else {
334    NOTREACHED();  // Chrome should not allow prefs to get into this state.
335    return false;
336  }
337
338  if (location)
339    *location = loc;
340
341  return true;
342}
343
344// static
345void ExternalProviderImpl::CreateExternalProviders(
346    VisitorInterface* service,
347    Profile* profile,
348    ProviderCollection* provider_list) {
349  // Policies are mandatory so they can't be skipped with command line flag.
350  provider_list->push_back(
351      linked_ptr<ExternalProviderInterface>(
352          new ExternalProviderImpl(
353              service,
354              new ExternalPolicyLoader(profile),
355              profile,
356              Manifest::INVALID_LOCATION,
357              Manifest::EXTERNAL_POLICY_DOWNLOAD,
358              Extension::NO_FLAGS)));
359
360  // In tests don't install extensions from default external sources.
361  // It would only slowdown tests and make them flaky.
362  if (CommandLine::ForCurrentProcess()->HasSwitch(
363      switches::kDisableDefaultApps))
364    return;
365
366  // No external app install in app mode.
367  if (chrome::IsRunningInForcedAppMode())
368    return;
369
370  // On Mac OS, items in /Library/... should be written by the superuser.
371  // Check that all components of the path are writable by root only.
372  ExternalPrefLoader::Options check_admin_permissions_on_mac;
373#if defined(OS_MACOSX)
374  check_admin_permissions_on_mac =
375    ExternalPrefLoader::ENSURE_PATH_CONTROLLED_BY_ADMIN;
376#else
377  check_admin_permissions_on_mac = ExternalPrefLoader::NONE;
378#endif
379
380  bool is_chromeos_demo_session = false;
381  int bundled_extension_creation_flags = Extension::NO_FLAGS;
382#if defined(OS_CHROMEOS)
383  chromeos::UserManager* user_manager = chromeos::UserManager::Get();
384  is_chromeos_demo_session =
385      user_manager && user_manager->IsLoggedInAsDemoUser() &&
386      g_browser_process->browser_policy_connector()->GetDeviceMode() ==
387          policy::DEVICE_MODE_RETAIL_KIOSK;
388  bundled_extension_creation_flags = Extension::FROM_WEBSTORE |
389      Extension::WAS_INSTALLED_BY_DEFAULT;
390#endif
391
392#if defined(OS_LINUX) && !defined(OS_CHROMEOS)
393  if (!profile->IsManaged()) {
394    provider_list->push_back(
395        linked_ptr<ExternalProviderInterface>(
396            new ExternalProviderImpl(
397                service,
398                new ExternalPrefLoader(
399                    chrome::DIR_STANDALONE_EXTERNAL_EXTENSIONS,
400                    ExternalPrefLoader::NONE),
401                profile,
402                Manifest::EXTERNAL_PREF,
403                Manifest::EXTERNAL_PREF_DOWNLOAD,
404                bundled_extension_creation_flags)));
405  }
406#endif
407
408#if defined(OS_CHROMEOS)
409  if (!is_chromeos_demo_session) {
410    int external_apps_path_id = profile->IsManaged() ?
411        chrome::DIR_MANAGED_USERS_DEFAULT_APPS :
412        chrome::DIR_STANDALONE_EXTERNAL_EXTENSIONS;
413    provider_list->push_back(
414        linked_ptr<ExternalProviderInterface>(
415            new ExternalProviderImpl(
416                service,
417                new chromeos::ExternalPrefCacheLoader(external_apps_path_id),
418                profile,
419                Manifest::EXTERNAL_PREF,
420                Manifest::EXTERNAL_PREF_DOWNLOAD,
421                bundled_extension_creation_flags)));
422  }
423
424  policy::AppPackUpdater* app_pack_updater =
425      g_browser_process->browser_policy_connector()->GetAppPackUpdater();
426  if (is_chromeos_demo_session && app_pack_updater &&
427      !app_pack_updater->created_external_loader()) {
428    provider_list->push_back(
429        linked_ptr<ExternalProviderInterface>(
430          new ExternalProviderImpl(
431              service,
432              app_pack_updater->CreateExternalLoader(),
433              profile,
434              Manifest::EXTERNAL_PREF,
435              Manifest::INVALID_LOCATION,
436              Extension::NO_FLAGS)));
437  }
438#endif
439
440  if (!profile->IsManaged() && !is_chromeos_demo_session) {
441    provider_list->push_back(
442        linked_ptr<ExternalProviderInterface>(
443            new ExternalProviderImpl(
444                service,
445                new ExternalPrefLoader(chrome::DIR_EXTERNAL_EXTENSIONS,
446                                       check_admin_permissions_on_mac),
447                profile,
448                Manifest::EXTERNAL_PREF,
449                Manifest::EXTERNAL_PREF_DOWNLOAD,
450                bundled_extension_creation_flags)));
451
452#if defined(OS_CHROMEOS) || defined (OS_MACOSX)
453    // Define a per-user source of external extensions.
454    // On Chrome OS, this serves as a source for OEM customization.
455    provider_list->push_back(
456        linked_ptr<ExternalProviderInterface>(
457            new ExternalProviderImpl(
458                service,
459                new ExternalPrefLoader(chrome::DIR_USER_EXTERNAL_EXTENSIONS,
460                                       ExternalPrefLoader::NONE),
461                profile,
462                Manifest::EXTERNAL_PREF,
463                Manifest::EXTERNAL_PREF_DOWNLOAD,
464                Extension::NO_FLAGS)));
465#endif
466
467#if defined(OS_WIN)
468    provider_list->push_back(
469        linked_ptr<ExternalProviderInterface>(
470            new ExternalProviderImpl(
471                service,
472                new ExternalRegistryLoader,
473                profile,
474                Manifest::EXTERNAL_REGISTRY,
475                Manifest::INVALID_LOCATION,
476                Extension::NO_FLAGS)));
477#endif
478
479#if !defined(OS_CHROMEOS)
480    // The default apps are installed as INTERNAL but use the external
481    // extension installer codeflow.
482    provider_list->push_back(
483        linked_ptr<ExternalProviderInterface>(
484            new default_apps::Provider(
485                profile,
486                service,
487                new ExternalPrefLoader(chrome::DIR_DEFAULT_APPS,
488                                       ExternalPrefLoader::NONE),
489                Manifest::INTERNAL,
490                Manifest::INVALID_LOCATION,
491                Extension::FROM_WEBSTORE |
492                    Extension::WAS_INSTALLED_BY_DEFAULT)));
493#endif
494
495    provider_list->push_back(
496      linked_ptr<ExternalProviderInterface>(
497        new ExternalProviderImpl(
498            service,
499            new ExternalComponentLoader(),
500            profile,
501            Manifest::INVALID_LOCATION,
502            Manifest::EXTERNAL_COMPONENT,
503            Extension::FROM_WEBSTORE | Extension::WAS_INSTALLED_BY_DEFAULT)));
504  }
505}
506
507}  // namespace extensions
508