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