1 // Copyright 2014 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/browser/api/runtime/runtime_api.h"
9 #include "base/lazy_instance.h"
10 #include "base/logging.h"
11 #include "base/memory/scoped_ptr.h"
12 #include "base/metrics/histogram.h"
13 #include "base/values.h"
14 #include "base/version.h"
15 #include "content/public/browser/browser_context.h"
16 #include "content/public/browser/child_process_security_policy.h"
17 #include "content/public/browser/notification_service.h"
18 #include "content/public/browser/render_frame_host.h"
19 #include "content/public/browser/render_process_host.h"
20 #include "extensions/browser/api/runtime/runtime_api_delegate.h"
21 #include "extensions/browser/event_router.h"
22 #include "extensions/browser/extension_host.h"
23 #include "extensions/browser/extension_prefs.h"
24 #include "extensions/browser/extension_registry.h"
25 #include "extensions/browser/extension_system.h"
26 #include "extensions/browser/extension_util.h"
27 #include "extensions/browser/extensions_browser_client.h"
28 #include "extensions/browser/lazy_background_task_queue.h"
29 #include "extensions/browser/notification_types.h"
30 #include "extensions/browser/process_manager_factory.h"
31 #include "extensions/common/api/runtime.h"
32 #include "extensions/common/error_utils.h"
33 #include "extensions/common/extension.h"
34 #include "extensions/common/manifest_handlers/background_info.h"
35 #include "extensions/common/manifest_handlers/shared_module_info.h"
36 #include "storage/browser/fileapi/isolated_context.h"
39 using content::BrowserContext
;
41 namespace extensions
{
43 namespace runtime
= core_api::runtime
;
47 const char kNoBackgroundPageError
[] = "You do not have a background page.";
48 const char kPageLoadError
[] = "Background page failed to load.";
49 const char kFailedToCreateOptionsPage
[] = "Could not create an options page.";
50 const char kInstallId
[] = "id";
51 const char kInstallReason
[] = "reason";
52 const char kInstallReasonChromeUpdate
[] = "chrome_update";
53 const char kInstallReasonUpdate
[] = "update";
54 const char kInstallReasonInstall
[] = "install";
55 const char kInstallReasonSharedModuleUpdate
[] = "shared_module_update";
56 const char kInstallPreviousVersion
[] = "previousVersion";
57 const char kInvalidUrlError
[] = "Invalid URL.";
58 const char kPlatformInfoUnavailable
[] = "Platform information unavailable.";
60 const char kUpdatesDisabledError
[] = "Autoupdate is not enabled.";
62 // A preference key storing the url loaded when an extension is uninstalled.
63 const char kUninstallUrl
[] = "uninstall_url";
65 // The name of the directory to be returned by getPackageDirectoryEntry. This
66 // particular value does not matter to user code, but is chosen for consistency
67 // with the equivalent Pepper API.
68 const char kPackageDirectoryPath
[] = "crxfs";
70 void DispatchOnStartupEventImpl(BrowserContext
* browser_context
,
71 const std::string
& extension_id
,
73 ExtensionHost
* host
) {
74 // A NULL host from the LazyBackgroundTaskQueue means the page failed to
76 if (!host
&& !first_call
)
79 // Don't send onStartup events to incognito browser contexts.
80 if (browser_context
->IsOffTheRecord())
83 if (ExtensionsBrowserClient::Get()->IsShuttingDown() ||
84 !ExtensionsBrowserClient::Get()->IsValidContext(browser_context
))
86 ExtensionSystem
* system
= ExtensionSystem::Get(browser_context
);
90 // If this is a persistent background page, we want to wait for it to load
91 // (it might not be ready, since this is startup). But only enqueue once.
92 // If it fails to load the first time, don't bother trying again.
93 const Extension
* extension
=
94 ExtensionRegistry::Get(browser_context
)->enabled_extensions().GetByID(
96 if (extension
&& BackgroundInfo::HasPersistentBackgroundPage(extension
) &&
98 LazyBackgroundTaskQueue::Get(browser_context
)
99 ->ShouldEnqueueTask(browser_context
, extension
)) {
100 LazyBackgroundTaskQueue::Get(browser_context
)
101 ->AddPendingTask(browser_context
, extension_id
,
102 base::Bind(&DispatchOnStartupEventImpl
,
103 browser_context
, extension_id
, false));
107 scoped_ptr
<base::ListValue
> event_args(new base::ListValue());
108 scoped_ptr
<Event
> event(new Event(
109 events::UNKNOWN
, runtime::OnStartup::kEventName
, event_args
.Pass()));
110 EventRouter::Get(browser_context
)
111 ->DispatchEventToExtension(extension_id
, event
.Pass());
114 void SetUninstallURL(ExtensionPrefs
* prefs
,
115 const std::string
& extension_id
,
116 const std::string
& url_string
) {
117 prefs
->UpdateExtensionPref(
118 extension_id
, kUninstallUrl
, new base::StringValue(url_string
));
121 std::string
GetUninstallURL(ExtensionPrefs
* prefs
,
122 const std::string
& extension_id
) {
123 std::string url_string
;
124 prefs
->ReadPrefAsString(extension_id
, kUninstallUrl
, &url_string
);
130 ///////////////////////////////////////////////////////////////////////////////
132 static base::LazyInstance
<BrowserContextKeyedAPIFactory
<RuntimeAPI
> >
133 g_factory
= LAZY_INSTANCE_INITIALIZER
;
136 BrowserContextKeyedAPIFactory
<RuntimeAPI
>* RuntimeAPI::GetFactoryInstance() {
137 return g_factory
.Pointer();
141 void BrowserContextKeyedAPIFactory
<RuntimeAPI
>::DeclareFactoryDependencies() {
142 DependsOn(ProcessManagerFactory::GetInstance());
145 RuntimeAPI::RuntimeAPI(content::BrowserContext
* context
)
146 : browser_context_(context
),
147 dispatch_chrome_updated_event_(false),
148 extension_registry_observer_(this),
149 process_manager_observer_(this) {
150 // RuntimeAPI is redirected in incognito, so |browser_context_| is never
152 DCHECK(!browser_context_
->IsOffTheRecord());
155 extensions::NOTIFICATION_EXTENSIONS_READY_DEPRECATED
,
156 content::Source
<BrowserContext
>(context
));
157 extension_registry_observer_
.Add(ExtensionRegistry::Get(browser_context_
));
158 process_manager_observer_
.Add(ProcessManager::Get(browser_context_
));
160 delegate_
= ExtensionsBrowserClient::Get()->CreateRuntimeAPIDelegate(
163 // Check if registered events are up-to-date. We can only do this once
164 // per browser context, since it updates internal state when called.
165 dispatch_chrome_updated_event_
=
166 ExtensionsBrowserClient::Get()->DidVersionUpdate(browser_context_
);
169 RuntimeAPI::~RuntimeAPI() {
172 void RuntimeAPI::Observe(int type
,
173 const content::NotificationSource
& source
,
174 const content::NotificationDetails
& details
) {
175 DCHECK_EQ(extensions::NOTIFICATION_EXTENSIONS_READY_DEPRECATED
, type
);
176 // We're done restarting Chrome after an update.
177 dispatch_chrome_updated_event_
= false;
179 delegate_
->AddUpdateObserver(this);
182 void RuntimeAPI::OnExtensionLoaded(content::BrowserContext
* browser_context
,
183 const Extension
* extension
) {
184 if (!dispatch_chrome_updated_event_
)
187 // Dispatch the onInstalled event with reason "chrome_update".
188 base::MessageLoop::current()->PostTask(
190 base::Bind(&RuntimeEventRouter::DispatchOnInstalledEvent
,
197 void RuntimeAPI::OnExtensionWillBeInstalled(
198 content::BrowserContext
* browser_context
,
199 const Extension
* extension
,
202 const std::string
& old_name
) {
203 // Ephemeral apps are not considered to be installed and do not receive
204 // the onInstalled() event.
205 if (util::IsEphemeralApp(extension
->id(), browser_context_
))
208 Version old_version
= delegate_
->GetPreviousExtensionVersion(extension
);
210 // Dispatch the onInstalled event.
211 base::MessageLoop::current()->PostTask(
213 base::Bind(&RuntimeEventRouter::DispatchOnInstalledEvent
,
220 void RuntimeAPI::OnExtensionUninstalled(
221 content::BrowserContext
* browser_context
,
222 const Extension
* extension
,
223 UninstallReason reason
) {
224 // Ephemeral apps are not considered to be installed, so the uninstall URL
225 // is not invoked when they are removed.
226 if (util::IsEphemeralApp(extension
->id(), browser_context_
))
229 RuntimeEventRouter::OnExtensionUninstalled(
230 browser_context_
, extension
->id(), reason
);
233 void RuntimeAPI::Shutdown() {
234 delegate_
->RemoveUpdateObserver(this);
237 void RuntimeAPI::OnAppUpdateAvailable(const Extension
* extension
) {
238 RuntimeEventRouter::DispatchOnUpdateAvailableEvent(
239 browser_context_
, extension
->id(), extension
->manifest()->value());
242 void RuntimeAPI::OnChromeUpdateAvailable() {
243 RuntimeEventRouter::DispatchOnBrowserUpdateAvailableEvent(browser_context_
);
246 void RuntimeAPI::OnBackgroundHostStartup(const Extension
* extension
) {
247 RuntimeEventRouter::DispatchOnStartupEvent(browser_context_
, extension
->id());
250 void RuntimeAPI::ReloadExtension(const std::string
& extension_id
) {
251 delegate_
->ReloadExtension(extension_id
);
254 bool RuntimeAPI::CheckForUpdates(
255 const std::string
& extension_id
,
256 const RuntimeAPIDelegate::UpdateCheckCallback
& callback
) {
257 return delegate_
->CheckForUpdates(extension_id
, callback
);
260 void RuntimeAPI::OpenURL(const GURL
& update_url
) {
261 delegate_
->OpenURL(update_url
);
264 bool RuntimeAPI::GetPlatformInfo(runtime::PlatformInfo
* info
) {
265 return delegate_
->GetPlatformInfo(info
);
268 bool RuntimeAPI::RestartDevice(std::string
* error_message
) {
269 return delegate_
->RestartDevice(error_message
);
272 bool RuntimeAPI::OpenOptionsPage(const Extension
* extension
) {
273 return delegate_
->OpenOptionsPage(extension
);
276 ///////////////////////////////////////////////////////////////////////////////
279 void RuntimeEventRouter::DispatchOnStartupEvent(
280 content::BrowserContext
* context
,
281 const std::string
& extension_id
) {
282 DispatchOnStartupEventImpl(context
, extension_id
, true, NULL
);
286 void RuntimeEventRouter::DispatchOnInstalledEvent(
287 content::BrowserContext
* context
,
288 const std::string
& extension_id
,
289 const Version
& old_version
,
290 bool chrome_updated
) {
291 if (!ExtensionsBrowserClient::Get()->IsValidContext(context
))
293 ExtensionSystem
* system
= ExtensionSystem::Get(context
);
297 scoped_ptr
<base::ListValue
> event_args(new base::ListValue());
298 base::DictionaryValue
* info
= new base::DictionaryValue();
299 event_args
->Append(info
);
300 if (old_version
.IsValid()) {
301 info
->SetString(kInstallReason
, kInstallReasonUpdate
);
302 info
->SetString(kInstallPreviousVersion
, old_version
.GetString());
303 } else if (chrome_updated
) {
304 info
->SetString(kInstallReason
, kInstallReasonChromeUpdate
);
306 info
->SetString(kInstallReason
, kInstallReasonInstall
);
308 EventRouter
* event_router
= EventRouter::Get(context
);
309 DCHECK(event_router
);
310 scoped_ptr
<Event
> event(new Event(
311 events::UNKNOWN
, runtime::OnInstalled::kEventName
, event_args
.Pass()));
312 event_router
->DispatchEventWithLazyListener(extension_id
, event
.Pass());
314 if (old_version
.IsValid()) {
315 const Extension
* extension
=
316 ExtensionRegistry::Get(context
)->enabled_extensions().GetByID(
318 if (extension
&& SharedModuleInfo::IsSharedModule(extension
)) {
319 scoped_ptr
<ExtensionSet
> dependents
=
320 system
->GetDependentExtensions(extension
);
321 for (ExtensionSet::const_iterator i
= dependents
->begin();
322 i
!= dependents
->end();
324 scoped_ptr
<base::ListValue
> sm_event_args(new base::ListValue());
325 base::DictionaryValue
* sm_info
= new base::DictionaryValue();
326 sm_event_args
->Append(sm_info
);
327 sm_info
->SetString(kInstallReason
, kInstallReasonSharedModuleUpdate
);
328 sm_info
->SetString(kInstallPreviousVersion
, old_version
.GetString());
329 sm_info
->SetString(kInstallId
, extension_id
);
330 scoped_ptr
<Event
> sm_event(new Event(events::UNKNOWN
,
331 runtime::OnInstalled::kEventName
,
332 sm_event_args
.Pass()));
333 event_router
->DispatchEventWithLazyListener((*i
)->id(),
341 void RuntimeEventRouter::DispatchOnUpdateAvailableEvent(
342 content::BrowserContext
* context
,
343 const std::string
& extension_id
,
344 const base::DictionaryValue
* manifest
) {
345 ExtensionSystem
* system
= ExtensionSystem::Get(context
);
349 scoped_ptr
<base::ListValue
> args(new base::ListValue
);
350 args
->Append(manifest
->DeepCopy());
351 EventRouter
* event_router
= EventRouter::Get(context
);
352 DCHECK(event_router
);
353 scoped_ptr
<Event
> event(new Event(
354 events::UNKNOWN
, runtime::OnUpdateAvailable::kEventName
, args
.Pass()));
355 event_router
->DispatchEventToExtension(extension_id
, event
.Pass());
359 void RuntimeEventRouter::DispatchOnBrowserUpdateAvailableEvent(
360 content::BrowserContext
* context
) {
361 ExtensionSystem
* system
= ExtensionSystem::Get(context
);
365 scoped_ptr
<base::ListValue
> args(new base::ListValue
);
366 EventRouter
* event_router
= EventRouter::Get(context
);
367 DCHECK(event_router
);
368 scoped_ptr
<Event
> event(
369 new Event(events::UNKNOWN
, runtime::OnBrowserUpdateAvailable::kEventName
,
371 event_router
->BroadcastEvent(event
.Pass());
375 void RuntimeEventRouter::DispatchOnRestartRequiredEvent(
376 content::BrowserContext
* context
,
377 const std::string
& app_id
,
378 core_api::runtime::OnRestartRequiredReason reason
) {
379 ExtensionSystem
* system
= ExtensionSystem::Get(context
);
383 scoped_ptr
<Event
> event(
384 new Event(events::UNKNOWN
, runtime::OnRestartRequired::kEventName
,
385 core_api::runtime::OnRestartRequired::Create(reason
)));
386 EventRouter
* event_router
= EventRouter::Get(context
);
387 DCHECK(event_router
);
388 event_router
->DispatchEventToExtension(app_id
, event
.Pass());
392 void RuntimeEventRouter::OnExtensionUninstalled(
393 content::BrowserContext
* context
,
394 const std::string
& extension_id
,
395 UninstallReason reason
) {
396 if (!(reason
== UNINSTALL_REASON_USER_INITIATED
||
397 reason
== UNINSTALL_REASON_MANAGEMENT_API
)) {
402 GetUninstallURL(ExtensionPrefs::Get(context
), extension_id
));
404 if (uninstall_url
.is_empty())
407 RuntimeAPI::GetFactoryInstance()->Get(context
)->OpenURL(uninstall_url
);
410 ExtensionFunction::ResponseAction
RuntimeGetBackgroundPageFunction::Run() {
411 ExtensionHost
* host
= ProcessManager::Get(browser_context())
412 ->GetBackgroundHostForExtension(extension_id());
413 if (LazyBackgroundTaskQueue::Get(browser_context())
414 ->ShouldEnqueueTask(browser_context(), extension())) {
415 LazyBackgroundTaskQueue::Get(browser_context())
417 browser_context(), extension_id(),
418 base::Bind(&RuntimeGetBackgroundPageFunction::OnPageLoaded
, this));
422 return RespondNow(Error(kNoBackgroundPageError
));
425 return RespondLater();
428 void RuntimeGetBackgroundPageFunction::OnPageLoaded(ExtensionHost
* host
) {
430 Respond(NoArguments());
432 Respond(Error(kPageLoadError
));
436 ExtensionFunction::ResponseAction
RuntimeOpenOptionsPageFunction::Run() {
437 RuntimeAPI
* api
= RuntimeAPI::GetFactoryInstance()->Get(browser_context());
438 return RespondNow(api
->OpenOptionsPage(extension())
440 : Error(kFailedToCreateOptionsPage
));
443 ExtensionFunction::ResponseAction
RuntimeSetUninstallURLFunction::Run() {
444 std::string url_string
;
445 EXTENSION_FUNCTION_VALIDATE(args_
->GetString(0, &url_string
));
447 GURL
url(url_string
);
448 if (!url
.is_valid()) {
450 Error(ErrorUtils::FormatErrorMessage(kInvalidUrlError
, url_string
)));
453 ExtensionPrefs::Get(browser_context()), extension_id(), url_string
);
454 return RespondNow(NoArguments());
457 ExtensionFunction::ResponseAction
RuntimeReloadFunction::Run() {
458 RuntimeAPI::GetFactoryInstance()->Get(browser_context())->ReloadExtension(
460 return RespondNow(NoArguments());
463 ExtensionFunction::ResponseAction
RuntimeRequestUpdateCheckFunction::Run() {
464 if (!RuntimeAPI::GetFactoryInstance()
465 ->Get(browser_context())
468 base::Bind(&RuntimeRequestUpdateCheckFunction::CheckComplete
,
470 return RespondNow(Error(kUpdatesDisabledError
));
472 return RespondLater();
475 void RuntimeRequestUpdateCheckFunction::CheckComplete(
476 const RuntimeAPIDelegate::UpdateCheckResult
& result
) {
477 if (result
.success
) {
478 base::DictionaryValue
* details
= new base::DictionaryValue
;
479 details
->SetString("version", result
.version
);
480 Respond(TwoArguments(new base::StringValue(result
.response
), details
));
482 // HMM(kalman): Why does !success not imply Error()?
483 Respond(OneArgument(new base::StringValue(result
.response
)));
487 ExtensionFunction::ResponseAction
RuntimeRestartFunction::Run() {
490 RuntimeAPI::GetFactoryInstance()->Get(browser_context())->RestartDevice(
493 return RespondNow(Error(message
));
495 return RespondNow(NoArguments());
498 ExtensionFunction::ResponseAction
RuntimeGetPlatformInfoFunction::Run() {
499 runtime::PlatformInfo info
;
500 if (!RuntimeAPI::GetFactoryInstance()
501 ->Get(browser_context())
502 ->GetPlatformInfo(&info
)) {
503 return RespondNow(Error(kPlatformInfoUnavailable
));
506 ArgumentList(runtime::GetPlatformInfo::Results::Create(info
)));
509 ExtensionFunction::ResponseAction
510 RuntimeGetPackageDirectoryEntryFunction::Run() {
511 storage::IsolatedContext
* isolated_context
=
512 storage::IsolatedContext::GetInstance();
513 DCHECK(isolated_context
);
515 std::string relative_path
= kPackageDirectoryPath
;
516 base::FilePath path
= extension_
->path();
517 std::string filesystem_id
= isolated_context
->RegisterFileSystemForPath(
518 storage::kFileSystemTypeNativeLocal
, std::string(), path
, &relative_path
);
520 int renderer_id
= render_frame_host()->GetProcess()->GetID();
521 content::ChildProcessSecurityPolicy
* policy
=
522 content::ChildProcessSecurityPolicy::GetInstance();
523 policy
->GrantReadFileSystem(renderer_id
, filesystem_id
);
524 base::DictionaryValue
* dict
= new base::DictionaryValue();
525 dict
->SetString("fileSystemId", filesystem_id
);
526 dict
->SetString("baseName", relative_path
);
527 return RespondNow(OneArgument(dict
));
530 } // namespace extensions