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.
4
5#include "extensions/browser/lazy_background_task_queue.h"
6
7#include "base/callback.h"
8#include "chrome/browser/chrome_notification_types.h"
9#include "chrome/browser/extensions/extension_host.h"
10#include "chrome/browser/extensions/extension_service.h"
11#include "chrome/browser/extensions/extension_system.h"
12#include "chrome/common/extensions/extension_messages.h"
13#include "content/public/browser/browser_context.h"
14#include "content/public/browser/notification_service.h"
15#include "content/public/browser/render_process_host.h"
16#include "content/public/browser/render_view_host.h"
17#include "content/public/browser/site_instance.h"
18#include "content/public/browser/web_contents.h"
19#include "extensions/browser/extensions_browser_client.h"
20#include "extensions/browser/process_manager.h"
21#include "extensions/browser/process_map.h"
22#include "extensions/common/extension.h"
23#include "extensions/common/manifest_handlers/background_info.h"
24#include "extensions/common/view_type.h"
25
26namespace extensions {
27
28LazyBackgroundTaskQueue::LazyBackgroundTaskQueue(
29    content::BrowserContext* browser_context)
30    : browser_context_(browser_context) {
31  registrar_.Add(this, chrome::NOTIFICATION_EXTENSION_HOST_DID_STOP_LOADING,
32                 content::NotificationService::AllBrowserContextsAndSources());
33  registrar_.Add(this, chrome::NOTIFICATION_EXTENSION_HOST_DESTROYED,
34                 content::NotificationService::AllBrowserContextsAndSources());
35  registrar_.Add(this, chrome::NOTIFICATION_EXTENSION_UNLOADED,
36                 content::Source<content::BrowserContext>(browser_context));
37}
38
39LazyBackgroundTaskQueue::~LazyBackgroundTaskQueue() {
40}
41
42bool LazyBackgroundTaskQueue::ShouldEnqueueTask(
43    content::BrowserContext* browser_context,
44    const Extension* extension) {
45  DCHECK(extension);
46  if (BackgroundInfo::HasBackgroundPage(extension)) {
47    ProcessManager* pm = ExtensionSystem::GetForBrowserContext(
48        browser_context)->process_manager();
49    DCHECK(pm);
50    ExtensionHost* background_host =
51        pm->GetBackgroundHostForExtension(extension->id());
52    if (!background_host || !background_host->did_stop_loading())
53      return true;
54    if (pm->IsBackgroundHostClosing(extension->id()))
55      pm->CancelSuspend(extension);
56  }
57
58  return false;
59}
60
61void LazyBackgroundTaskQueue::AddPendingTask(
62    content::BrowserContext* browser_context,
63    const std::string& extension_id,
64    const PendingTask& task) {
65  if (ExtensionsBrowserClient::Get()->IsShuttingDown()) {
66    task.Run(NULL);
67    return;
68  }
69  PendingTasksList* tasks_list = NULL;
70  PendingTasksKey key(browser_context, extension_id);
71  PendingTasksMap::iterator it = pending_tasks_.find(key);
72  if (it == pending_tasks_.end()) {
73    tasks_list = new PendingTasksList();
74    pending_tasks_[key] = linked_ptr<PendingTasksList>(tasks_list);
75
76    ExtensionService* extension_service = ExtensionSystem::GetForBrowserContext(
77        browser_context)->extension_service();
78    DCHECK(extension_service);
79    const Extension* extension =
80        extension_service->extensions()->GetByID(extension_id);
81    if (extension && BackgroundInfo::HasLazyBackgroundPage(extension)) {
82      // If this is the first enqueued task, and we're not waiting for the
83      // background page to unload, ensure the background page is loaded.
84      ProcessManager* pm = ExtensionSystem::GetForBrowserContext(
85          browser_context)->process_manager();
86      pm->IncrementLazyKeepaliveCount(extension);
87      // Creating the background host may fail, e.g. if |profile| is incognito
88      // but the extension isn't enabled in incognito mode.
89      if (!pm->CreateBackgroundHost(
90            extension, BackgroundInfo::GetBackgroundURL(extension))) {
91        task.Run(NULL);
92        return;
93      }
94    }
95  } else {
96    tasks_list = it->second.get();
97  }
98
99  tasks_list->push_back(task);
100}
101
102void LazyBackgroundTaskQueue::ProcessPendingTasks(
103    ExtensionHost* host,
104    content::BrowserContext* browser_context,
105    const Extension* extension) {
106  if (!ExtensionsBrowserClient::Get()->IsSameContext(browser_context,
107                                                     browser_context_))
108    return;
109
110  PendingTasksKey key(browser_context, extension->id());
111  PendingTasksMap::iterator map_it = pending_tasks_.find(key);
112  if (map_it == pending_tasks_.end()) {
113    if (BackgroundInfo::HasLazyBackgroundPage(extension))
114      CHECK(!host);  // lazy page should not load without any pending tasks
115    return;
116  }
117
118  // Swap the pending tasks to a temporary, to avoid problems if the task
119  // list is modified during processing.
120  PendingTasksList tasks;
121  tasks.swap(*map_it->second);
122  for (PendingTasksList::const_iterator it = tasks.begin();
123       it != tasks.end(); ++it) {
124    it->Run(host);
125  }
126
127  pending_tasks_.erase(key);
128
129  // Balance the keepalive in AddPendingTask. Note we don't do this on a
130  // failure to load, because the keepalive count is reset in that case.
131  if (host && BackgroundInfo::HasLazyBackgroundPage(extension)) {
132    ExtensionSystem::GetForBrowserContext(browser_context)->process_manager()->
133        DecrementLazyKeepaliveCount(extension);
134  }
135}
136
137void LazyBackgroundTaskQueue::Observe(
138    int type,
139    const content::NotificationSource& source,
140    const content::NotificationDetails& details) {
141  switch (type) {
142    case chrome::NOTIFICATION_EXTENSION_HOST_DID_STOP_LOADING: {
143      // If an on-demand background page finished loading, dispatch queued up
144      // events for it.
145      ExtensionHost* host =
146          content::Details<ExtensionHost>(details).ptr();
147      if (host->extension_host_type() == VIEW_TYPE_EXTENSION_BACKGROUND_PAGE) {
148        CHECK(host->did_stop_loading());
149        ProcessPendingTasks(host, host->browser_context(), host->extension());
150      }
151      break;
152    }
153    case chrome::NOTIFICATION_EXTENSION_HOST_DESTROYED: {
154      // Notify consumers about the load failure when the background host dies.
155      // This can happen if the extension crashes. This is not strictly
156      // necessary, since we also unload the extension in that case (which
157      // dispatches the tasks below), but is a good extra precaution.
158      content::BrowserContext* browser_context =
159          content::Source<content::BrowserContext>(source).ptr();
160      ExtensionHost* host =
161           content::Details<ExtensionHost>(details).ptr();
162      if (host->extension_host_type() == VIEW_TYPE_EXTENSION_BACKGROUND_PAGE) {
163        ProcessPendingTasks(NULL, browser_context, host->extension());
164      }
165      break;
166    }
167    case chrome::NOTIFICATION_EXTENSION_UNLOADED: {
168      // Notify consumers that the page failed to load.
169      content::BrowserContext* browser_context =
170          content::Source<content::BrowserContext>(source).ptr();
171      UnloadedExtensionInfo* unloaded =
172          content::Details<UnloadedExtensionInfo>(details).ptr();
173      ProcessPendingTasks(NULL, browser_context, unloaded->extension);
174      // If this extension is also running in an off-the-record context,
175      // notify that task queue as well.
176      ExtensionsBrowserClient* browser_client = ExtensionsBrowserClient::Get();
177      if (browser_client->HasOffTheRecordContext(browser_context)) {
178        ProcessPendingTasks(
179            NULL,
180            browser_client->GetOffTheRecordContext(browser_context),
181            unloaded->extension);
182      }
183      break;
184    }
185    default:
186      NOTREACHED();
187      break;
188  }
189}
190
191}  // namespace extensions
192