Remove unused parameter.
[chromium-blink-merge.git] / extensions / browser / extension_function.cc
blob6a136b2c0613e69988afe123429e42314fb864ee
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.
5 #include "extensions/browser/extension_function.h"
7 #include "base/logging.h"
8 #include "base/memory/singleton.h"
9 #include "base/synchronization/lock.h"
10 #include "content/public/browser/notification_source.h"
11 #include "content/public/browser/notification_types.h"
12 #include "content/public/browser/render_frame_host.h"
13 #include "content/public/browser/render_view_host.h"
14 #include "content/public/browser/web_contents.h"
15 #include "content/public/browser/web_contents_observer.h"
16 #include "extensions/browser/extension_function_dispatcher.h"
17 #include "extensions/browser/extension_message_filter.h"
18 #include "extensions/common/error_utils.h"
19 #include "extensions/common/extension_api.h"
20 #include "extensions/common/extension_messages.h"
22 using content::BrowserThread;
23 using content::RenderViewHost;
24 using content::WebContents;
25 using extensions::ErrorUtils;
26 using extensions::ExtensionAPI;
27 using extensions::Feature;
29 namespace {
31 class ArgumentListResponseValue
32 : public ExtensionFunction::ResponseValueObject {
33 public:
34 ArgumentListResponseValue(const std::string& function_name,
35 const char* title,
36 ExtensionFunction* function,
37 scoped_ptr<base::ListValue> result)
38 : function_name_(function_name), title_(title) {
39 if (function->GetResultList()) {
40 DCHECK_EQ(function->GetResultList(), result.get())
41 << "The result set on this function (" << function_name_ << ") "
42 << "either by calling SetResult() or directly modifying |result_| is "
43 << "different to the one passed to " << title_ << "(). "
44 << "The best way to fix this problem is to exclusively use " << title_
45 << "(). SetResult() and |result_| are deprecated.";
46 } else {
47 function->SetResultList(result.Pass());
49 // It would be nice to DCHECK(error.empty()) but some legacy extension
50 // function implementations... I'm looking at chrome.input.ime... do this
51 // for some reason.
54 ~ArgumentListResponseValue() override {}
56 bool Apply() override { return true; }
58 private:
59 std::string function_name_;
60 const char* title_;
63 class ErrorWithArgumentsResponseValue : public ArgumentListResponseValue {
64 public:
65 ErrorWithArgumentsResponseValue(const std::string& function_name,
66 const char* title,
67 ExtensionFunction* function,
68 scoped_ptr<base::ListValue> result,
69 const std::string& error)
70 : ArgumentListResponseValue(function_name,
71 title,
72 function,
73 result.Pass()) {
74 function->SetError(error);
77 ~ErrorWithArgumentsResponseValue() override {}
79 bool Apply() override { return false; }
82 class ErrorResponseValue : public ExtensionFunction::ResponseValueObject {
83 public:
84 ErrorResponseValue(ExtensionFunction* function, const std::string& error) {
85 // It would be nice to DCHECK(!error.empty()) but too many legacy extension
86 // function implementations don't set error but signal failure.
87 function->SetError(error);
90 ~ErrorResponseValue() override {}
92 bool Apply() override { return false; }
95 class BadMessageResponseValue : public ExtensionFunction::ResponseValueObject {
96 public:
97 explicit BadMessageResponseValue(ExtensionFunction* function) {
98 function->set_bad_message(true);
99 NOTREACHED() << function->name() << ": bad message";
102 ~BadMessageResponseValue() override {}
104 bool Apply() override { return false; }
107 class RespondNowAction : public ExtensionFunction::ResponseActionObject {
108 public:
109 typedef base::Callback<void(bool)> SendResponseCallback;
110 RespondNowAction(ExtensionFunction::ResponseValue result,
111 const SendResponseCallback& send_response)
112 : result_(result.Pass()), send_response_(send_response) {}
113 ~RespondNowAction() override {}
115 void Execute() override { send_response_.Run(result_->Apply()); }
117 private:
118 ExtensionFunction::ResponseValue result_;
119 SendResponseCallback send_response_;
122 class RespondLaterAction : public ExtensionFunction::ResponseActionObject {
123 public:
124 ~RespondLaterAction() override {}
126 void Execute() override {}
129 // Used in implementation of ScopedUserGestureForTests.
130 class UserGestureForTests {
131 public:
132 static UserGestureForTests* GetInstance();
134 // Returns true if there is at least one ScopedUserGestureForTests object
135 // alive.
136 bool HaveGesture();
138 // These should be called when a ScopedUserGestureForTests object is
139 // created/destroyed respectively.
140 void IncrementCount();
141 void DecrementCount();
143 private:
144 UserGestureForTests();
145 friend struct DefaultSingletonTraits<UserGestureForTests>;
147 base::Lock lock_; // for protecting access to count_
148 int count_;
151 // static
152 UserGestureForTests* UserGestureForTests::GetInstance() {
153 return Singleton<UserGestureForTests>::get();
156 UserGestureForTests::UserGestureForTests() : count_(0) {}
158 bool UserGestureForTests::HaveGesture() {
159 base::AutoLock autolock(lock_);
160 return count_ > 0;
163 void UserGestureForTests::IncrementCount() {
164 base::AutoLock autolock(lock_);
165 ++count_;
168 void UserGestureForTests::DecrementCount() {
169 base::AutoLock autolock(lock_);
170 --count_;
174 } // namespace
176 // static
177 void ExtensionFunctionDeleteTraits::Destruct(const ExtensionFunction* x) {
178 x->Destruct();
181 // Helper class to track the lifetime of ExtensionFunction's RenderViewHost or
182 // RenderFrameHost pointer and NULL it out when it dies. It also allows us to
183 // filter IPC messages coming from the RenderViewHost/RenderFrameHost.
184 class UIThreadExtensionFunction::RenderHostTracker
185 : public content::WebContentsObserver {
186 public:
187 explicit RenderHostTracker(UIThreadExtensionFunction* function)
188 : content::WebContentsObserver(
189 function->render_view_host() ?
190 WebContents::FromRenderViewHost(function->render_view_host()) :
191 WebContents::FromRenderFrameHost(
192 function->render_frame_host())),
193 function_(function) {
196 private:
197 // content::WebContentsObserver:
198 void RenderViewDeleted(content::RenderViewHost* render_view_host) override {
199 if (render_view_host != function_->render_view_host())
200 return;
202 function_->SetRenderViewHost(NULL);
204 void RenderFrameDeleted(
205 content::RenderFrameHost* render_frame_host) override {
206 if (render_frame_host != function_->render_frame_host())
207 return;
209 function_->SetRenderFrameHost(NULL);
212 bool OnMessageReceived(const IPC::Message& message,
213 content::RenderFrameHost* render_frame_host) override {
214 DCHECK(render_frame_host);
215 if (render_frame_host == function_->render_frame_host())
216 return function_->OnMessageReceived(message);
217 else
218 return false;
221 bool OnMessageReceived(const IPC::Message& message) override {
222 return function_->OnMessageReceived(message);
225 UIThreadExtensionFunction* function_;
227 DISALLOW_COPY_AND_ASSIGN(RenderHostTracker);
230 ExtensionFunction::ExtensionFunction()
231 : request_id_(-1),
232 profile_id_(NULL),
233 name_(""),
234 has_callback_(false),
235 include_incognito_(false),
236 user_gesture_(false),
237 bad_message_(false),
238 histogram_value_(extensions::functions::UNKNOWN),
239 source_tab_id_(-1),
240 source_context_type_(Feature::UNSPECIFIED_CONTEXT) {
243 ExtensionFunction::~ExtensionFunction() {
246 UIThreadExtensionFunction* ExtensionFunction::AsUIThreadExtensionFunction() {
247 return NULL;
250 IOThreadExtensionFunction* ExtensionFunction::AsIOThreadExtensionFunction() {
251 return NULL;
254 bool ExtensionFunction::HasPermission() {
255 Feature::Availability availability =
256 ExtensionAPI::GetSharedInstance()->IsAvailable(
257 name_, extension_.get(), source_context_type_, source_url());
258 return availability.is_available();
261 void ExtensionFunction::OnQuotaExceeded(const std::string& violation_error) {
262 error_ = violation_error;
263 SendResponse(false);
266 void ExtensionFunction::SetArgs(const base::ListValue* args) {
267 DCHECK(!args_.get()); // Should only be called once.
268 args_.reset(args->DeepCopy());
271 void ExtensionFunction::SetResult(base::Value* result) {
272 results_.reset(new base::ListValue());
273 results_->Append(result);
276 void ExtensionFunction::SetResultList(scoped_ptr<base::ListValue> results) {
277 results_ = results.Pass();
280 const base::ListValue* ExtensionFunction::GetResultList() const {
281 return results_.get();
284 std::string ExtensionFunction::GetError() const {
285 return error_;
288 void ExtensionFunction::SetError(const std::string& error) {
289 error_ = error;
292 bool ExtensionFunction::user_gesture() const {
293 return user_gesture_ || UserGestureForTests::GetInstance()->HaveGesture();
296 ExtensionFunction::ResponseValue ExtensionFunction::NoArguments() {
297 return ResponseValue(new ArgumentListResponseValue(
298 name(), "NoArguments", this, make_scoped_ptr(new base::ListValue())));
301 ExtensionFunction::ResponseValue ExtensionFunction::OneArgument(
302 base::Value* arg) {
303 scoped_ptr<base::ListValue> args(new base::ListValue());
304 args->Append(arg);
305 return ResponseValue(
306 new ArgumentListResponseValue(name(), "OneArgument", this, args.Pass()));
309 ExtensionFunction::ResponseValue ExtensionFunction::TwoArguments(
310 base::Value* arg1,
311 base::Value* arg2) {
312 scoped_ptr<base::ListValue> args(new base::ListValue());
313 args->Append(arg1);
314 args->Append(arg2);
315 return ResponseValue(
316 new ArgumentListResponseValue(name(), "TwoArguments", this, args.Pass()));
319 ExtensionFunction::ResponseValue ExtensionFunction::ArgumentList(
320 scoped_ptr<base::ListValue> args) {
321 return ResponseValue(
322 new ArgumentListResponseValue(name(), "ArgumentList", this, args.Pass()));
325 ExtensionFunction::ResponseValue ExtensionFunction::Error(
326 const std::string& error) {
327 return ResponseValue(new ErrorResponseValue(this, error));
330 ExtensionFunction::ResponseValue ExtensionFunction::Error(
331 const std::string& format,
332 const std::string& s1) {
333 return ResponseValue(
334 new ErrorResponseValue(this, ErrorUtils::FormatErrorMessage(format, s1)));
337 ExtensionFunction::ResponseValue ExtensionFunction::Error(
338 const std::string& format,
339 const std::string& s1,
340 const std::string& s2) {
341 return ResponseValue(new ErrorResponseValue(
342 this, ErrorUtils::FormatErrorMessage(format, s1, s2)));
345 ExtensionFunction::ResponseValue ExtensionFunction::Error(
346 const std::string& format,
347 const std::string& s1,
348 const std::string& s2,
349 const std::string& s3) {
350 return ResponseValue(new ErrorResponseValue(
351 this, ErrorUtils::FormatErrorMessage(format, s1, s2, s3)));
354 ExtensionFunction::ResponseValue ExtensionFunction::ErrorWithArguments(
355 scoped_ptr<base::ListValue> args,
356 const std::string& error) {
357 return ResponseValue(new ErrorWithArgumentsResponseValue(
358 name(), "ErrorWithArguments", this, args.Pass(), error));
361 ExtensionFunction::ResponseValue ExtensionFunction::BadMessage() {
362 return ResponseValue(new BadMessageResponseValue(this));
365 ExtensionFunction::ResponseAction ExtensionFunction::RespondNow(
366 ResponseValue result) {
367 return ResponseAction(new RespondNowAction(
368 result.Pass(), base::Bind(&ExtensionFunction::SendResponse, this)));
371 ExtensionFunction::ResponseAction ExtensionFunction::RespondLater() {
372 return ResponseAction(new RespondLaterAction());
375 // static
376 ExtensionFunction::ResponseAction ExtensionFunction::ValidationFailure(
377 ExtensionFunction* function) {
378 return function->RespondNow(function->BadMessage());
381 void ExtensionFunction::Respond(ResponseValue result) {
382 SendResponse(result->Apply());
385 bool ExtensionFunction::ShouldSkipQuotaLimiting() const {
386 return false;
389 bool ExtensionFunction::HasOptionalArgument(size_t index) {
390 base::Value* value;
391 return args_->Get(index, &value) && !value->IsType(base::Value::TYPE_NULL);
394 void ExtensionFunction::SendResponseImpl(bool success) {
395 DCHECK(!response_callback_.is_null());
397 ResponseType type = success ? SUCCEEDED : FAILED;
398 if (bad_message_) {
399 type = BAD_MESSAGE;
400 LOG(ERROR) << "Bad extension message " << name_;
403 // If results were never set, we send an empty argument list.
404 if (!results_)
405 results_.reset(new base::ListValue());
407 response_callback_.Run(type, *results_, GetError(), histogram_value());
410 void ExtensionFunction::OnRespondingLater(ResponseValue value) {
411 SendResponse(value->Apply());
414 UIThreadExtensionFunction::UIThreadExtensionFunction()
415 : render_view_host_(NULL),
416 render_frame_host_(NULL),
417 context_(NULL),
418 delegate_(NULL) {
421 UIThreadExtensionFunction::~UIThreadExtensionFunction() {
422 if (dispatcher() && render_view_host())
423 dispatcher()->OnExtensionFunctionCompleted(extension());
426 UIThreadExtensionFunction*
427 UIThreadExtensionFunction::AsUIThreadExtensionFunction() {
428 return this;
431 bool UIThreadExtensionFunction::OnMessageReceived(const IPC::Message& message) {
432 return false;
435 void UIThreadExtensionFunction::Destruct() const {
436 BrowserThread::DeleteOnUIThread::Destruct(this);
439 void UIThreadExtensionFunction::SetRenderViewHost(
440 RenderViewHost* render_view_host) {
441 DCHECK(!render_frame_host_);
442 render_view_host_ = render_view_host;
443 tracker_.reset(render_view_host ? new RenderHostTracker(this) : NULL);
446 void UIThreadExtensionFunction::SetRenderFrameHost(
447 content::RenderFrameHost* render_frame_host) {
448 DCHECK(!render_view_host_);
449 render_frame_host_ = render_frame_host;
450 tracker_.reset(render_frame_host ? new RenderHostTracker(this) : NULL);
453 content::WebContents* UIThreadExtensionFunction::GetAssociatedWebContents() {
454 content::WebContents* web_contents = NULL;
455 if (dispatcher())
456 web_contents = dispatcher()->delegate()->GetAssociatedWebContents();
458 return web_contents;
461 content::WebContents* UIThreadExtensionFunction::GetSenderWebContents() {
462 return render_view_host_ ?
463 content::WebContents::FromRenderViewHost(render_view_host_) : nullptr;
466 void UIThreadExtensionFunction::SendResponse(bool success) {
467 if (delegate_)
468 delegate_->OnSendResponse(this, success, bad_message_);
469 else
470 SendResponseImpl(success);
472 if (!transferred_blob_uuids_.empty()) {
473 DCHECK(!delegate_) << "Blob transfer not supported with test delegate.";
474 GetIPCSender()->Send(
475 new ExtensionMsg_TransferBlobs(transferred_blob_uuids_));
479 void UIThreadExtensionFunction::SetTransferredBlobUUIDs(
480 const std::vector<std::string>& blob_uuids) {
481 DCHECK(transferred_blob_uuids_.empty()); // Should only be called once.
482 transferred_blob_uuids_ = blob_uuids;
485 void UIThreadExtensionFunction::WriteToConsole(
486 content::ConsoleMessageLevel level,
487 const std::string& message) {
488 GetIPCSender()->Send(
489 new ExtensionMsg_AddMessageToConsole(GetRoutingID(), level, message));
492 IPC::Sender* UIThreadExtensionFunction::GetIPCSender() {
493 if (render_view_host_)
494 return render_view_host_;
495 else
496 return render_frame_host_;
499 int UIThreadExtensionFunction::GetRoutingID() {
500 if (render_view_host_)
501 return render_view_host_->GetRoutingID();
502 else
503 return render_frame_host_->GetRoutingID();
506 IOThreadExtensionFunction::IOThreadExtensionFunction()
507 : routing_id_(MSG_ROUTING_NONE) {
510 IOThreadExtensionFunction::~IOThreadExtensionFunction() {
513 IOThreadExtensionFunction*
514 IOThreadExtensionFunction::AsIOThreadExtensionFunction() {
515 return this;
518 void IOThreadExtensionFunction::Destruct() const {
519 BrowserThread::DeleteOnIOThread::Destruct(this);
522 void IOThreadExtensionFunction::SendResponse(bool success) {
523 SendResponseImpl(success);
526 AsyncExtensionFunction::AsyncExtensionFunction() {
529 AsyncExtensionFunction::~AsyncExtensionFunction() {
532 ExtensionFunction::ScopedUserGestureForTests::ScopedUserGestureForTests() {
533 UserGestureForTests::GetInstance()->IncrementCount();
536 ExtensionFunction::ScopedUserGestureForTests::~ScopedUserGestureForTests() {
537 UserGestureForTests::GetInstance()->DecrementCount();
540 ExtensionFunction::ResponseAction AsyncExtensionFunction::Run() {
541 return RunAsync() ? RespondLater() : RespondNow(Error(error_));
544 // static
545 bool AsyncExtensionFunction::ValidationFailure(
546 AsyncExtensionFunction* function) {
547 return false;
550 SyncExtensionFunction::SyncExtensionFunction() {
553 SyncExtensionFunction::~SyncExtensionFunction() {
556 ExtensionFunction::ResponseAction SyncExtensionFunction::Run() {
557 return RespondNow(RunSync() ? ArgumentList(results_.Pass()) : Error(error_));
560 // static
561 bool SyncExtensionFunction::ValidationFailure(SyncExtensionFunction* function) {
562 return false;
565 SyncIOThreadExtensionFunction::SyncIOThreadExtensionFunction() {
568 SyncIOThreadExtensionFunction::~SyncIOThreadExtensionFunction() {
571 ExtensionFunction::ResponseAction SyncIOThreadExtensionFunction::Run() {
572 return RespondNow(RunSync() ? ArgumentList(results_.Pass()) : Error(error_));
575 // static
576 bool SyncIOThreadExtensionFunction::ValidationFailure(
577 SyncIOThreadExtensionFunction* function) {
578 return false;