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/extension_function.h"
6
7#include "base/logging.h"
8#include "base/metrics/sparse_histogram.h"
9#include "chrome/browser/extensions/extension_function_dispatcher.h"
10#include "chrome/browser/extensions/extension_service.h"
11#include "chrome/browser/renderer_host/chrome_render_message_filter.h"
12#include "chrome/common/extensions/extension_messages.h"
13#include "content/public/browser/notification_source.h"
14#include "content/public/browser/notification_types.h"
15#include "content/public/browser/render_view_host.h"
16#include "content/public/browser/web_contents.h"
17#include "content/public/browser/web_contents_observer.h"
18#include "extensions/common/extension_api.h"
19
20using content::BrowserThread;
21using content::RenderViewHost;
22using content::WebContents;
23using extensions::ExtensionAPI;
24using extensions::Feature;
25
26// static
27void ExtensionFunctionDeleteTraits::Destruct(const ExtensionFunction* x) {
28  x->Destruct();
29}
30
31// Helper class to track the lifetime of ExtensionFunction's RenderViewHost
32// pointer and NULL it out when it dies. It also allows us to filter IPC
33// messages coming from the RenderViewHost.
34class UIThreadExtensionFunction::RenderViewHostTracker
35    : public content::WebContentsObserver {
36 public:
37  explicit RenderViewHostTracker(UIThreadExtensionFunction* function)
38      : content::WebContentsObserver(
39            WebContents::FromRenderViewHost(function->render_view_host())),
40        function_(function) {
41  }
42
43 private:
44  // content::WebContentsObserver:
45  virtual void RenderViewDeleted(
46      content::RenderViewHost* render_view_host) OVERRIDE {
47    if (render_view_host != function_->render_view_host())
48      return;
49
50    function_->SetRenderViewHost(NULL);
51  }
52
53  virtual bool OnMessageReceived(const IPC::Message& message) OVERRIDE {
54    return function_->OnMessageReceivedFromRenderView(message);
55  }
56
57  UIThreadExtensionFunction* function_;
58
59  DISALLOW_COPY_AND_ASSIGN(RenderViewHostTracker);
60};
61
62ExtensionFunction::ExtensionFunction()
63    : request_id_(-1),
64      profile_id_(NULL),
65      has_callback_(false),
66      include_incognito_(false),
67      user_gesture_(false),
68      bad_message_(false),
69      histogram_value_(extensions::functions::UNKNOWN) {}
70
71ExtensionFunction::~ExtensionFunction() {
72}
73
74UIThreadExtensionFunction* ExtensionFunction::AsUIThreadExtensionFunction() {
75  return NULL;
76}
77
78IOThreadExtensionFunction* ExtensionFunction::AsIOThreadExtensionFunction() {
79  return NULL;
80}
81
82bool ExtensionFunction::HasPermission() {
83  Feature::Availability availability =
84      ExtensionAPI::GetSharedInstance()->IsAvailable(
85          name_, extension_, Feature::BLESSED_EXTENSION_CONTEXT, source_url());
86  return availability.is_available();
87}
88
89void ExtensionFunction::OnQuotaExceeded(const std::string& violation_error) {
90  error_ = violation_error;
91  SendResponse(false);
92}
93
94void ExtensionFunction::SetArgs(const base::ListValue* args) {
95  DCHECK(!args_.get());  // Should only be called once.
96  args_.reset(args->DeepCopy());
97}
98
99void ExtensionFunction::SetResult(base::Value* result) {
100  results_.reset(new base::ListValue());
101  results_->Append(result);
102}
103
104const base::ListValue* ExtensionFunction::GetResultList() {
105  return results_.get();
106}
107
108const std::string ExtensionFunction::GetError() {
109  return error_;
110}
111
112void ExtensionFunction::SetError(const std::string& error) {
113  error_ = error;
114}
115
116void ExtensionFunction::Run() {
117  UMA_HISTOGRAM_SPARSE_SLOWLY("Extensions.FunctionCalls", histogram_value());
118
119  if (!RunImpl())
120    SendResponse(false);
121}
122
123bool ExtensionFunction::ShouldSkipQuotaLimiting() const {
124  return false;
125}
126
127bool ExtensionFunction::HasOptionalArgument(size_t index) {
128  Value* value;
129  return args_->Get(index, &value) && !value->IsType(Value::TYPE_NULL);
130}
131
132void ExtensionFunction::SendResponseImpl(bool success) {
133  DCHECK(!response_callback_.is_null());
134
135  ResponseType type = success ? SUCCEEDED : FAILED;
136  if (bad_message_) {
137    type = BAD_MESSAGE;
138    LOG(ERROR) << "Bad extension message " << name_;
139  }
140
141  // If results were never set, we send an empty argument list.
142  if (!results_)
143    results_.reset(new base::ListValue());
144
145  response_callback_.Run(type, *results_, GetError());
146}
147
148UIThreadExtensionFunction::UIThreadExtensionFunction()
149    : render_view_host_(NULL), context_(NULL), delegate_(NULL) {}
150
151UIThreadExtensionFunction::~UIThreadExtensionFunction() {
152  if (dispatcher() && render_view_host())
153    dispatcher()->OnExtensionFunctionCompleted(GetExtension());
154}
155
156UIThreadExtensionFunction*
157UIThreadExtensionFunction::AsUIThreadExtensionFunction() {
158  return this;
159}
160
161bool UIThreadExtensionFunction::OnMessageReceivedFromRenderView(
162    const IPC::Message& message) {
163  return false;
164}
165
166void UIThreadExtensionFunction::Destruct() const {
167  BrowserThread::DeleteOnUIThread::Destruct(this);
168}
169
170void UIThreadExtensionFunction::SetRenderViewHost(
171    RenderViewHost* render_view_host) {
172  render_view_host_ = render_view_host;
173  tracker_.reset(render_view_host ? new RenderViewHostTracker(this) : NULL);
174}
175
176content::WebContents* UIThreadExtensionFunction::GetAssociatedWebContents() {
177  content::WebContents* web_contents = NULL;
178  if (dispatcher())
179    web_contents = dispatcher()->delegate()->GetAssociatedWebContents();
180
181  return web_contents;
182}
183
184void UIThreadExtensionFunction::SendResponse(bool success) {
185  if (delegate_)
186    delegate_->OnSendResponse(this, success, bad_message_);
187  else
188    SendResponseImpl(success);
189}
190
191void UIThreadExtensionFunction::WriteToConsole(
192    content::ConsoleMessageLevel level,
193    const std::string& message) {
194  render_view_host_->Send(new ExtensionMsg_AddMessageToConsole(
195      render_view_host_->GetRoutingID(), level, message));
196}
197
198IOThreadExtensionFunction::IOThreadExtensionFunction()
199    : routing_id_(MSG_ROUTING_NONE) {
200}
201
202IOThreadExtensionFunction::~IOThreadExtensionFunction() {
203}
204
205IOThreadExtensionFunction*
206IOThreadExtensionFunction::AsIOThreadExtensionFunction() {
207  return this;
208}
209
210void IOThreadExtensionFunction::Destruct() const {
211  BrowserThread::DeleteOnIOThread::Destruct(this);
212}
213
214void IOThreadExtensionFunction::SendResponse(bool success) {
215  SendResponseImpl(success);
216}
217
218AsyncExtensionFunction::AsyncExtensionFunction() {
219}
220
221AsyncExtensionFunction::~AsyncExtensionFunction() {
222}
223
224SyncExtensionFunction::SyncExtensionFunction() {
225}
226
227SyncExtensionFunction::~SyncExtensionFunction() {
228}
229
230void SyncExtensionFunction::Run() {
231  SendResponse(RunImpl());
232}
233
234SyncIOThreadExtensionFunction::SyncIOThreadExtensionFunction() {
235}
236
237SyncIOThreadExtensionFunction::~SyncIOThreadExtensionFunction() {
238}
239
240void SyncIOThreadExtensionFunction::Run() {
241  SendResponse(RunImpl());
242}
243