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