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
;
31 class ArgumentListResponseValue
32 : public ExtensionFunction::ResponseValueObject
{
34 ArgumentListResponseValue(const std::string
& function_name
,
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.";
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
54 ~ArgumentListResponseValue() override
{}
56 bool Apply() override
{ return true; }
59 std::string function_name_
;
63 class ErrorWithArgumentsResponseValue
: public ArgumentListResponseValue
{
65 ErrorWithArgumentsResponseValue(const std::string
& function_name
,
67 ExtensionFunction
* function
,
68 scoped_ptr
<base::ListValue
> result
,
69 const std::string
& error
)
70 : ArgumentListResponseValue(function_name
,
74 function
->SetError(error
);
77 ~ErrorWithArgumentsResponseValue() override
{}
79 bool Apply() override
{ return false; }
82 class ErrorResponseValue
: public ExtensionFunction::ResponseValueObject
{
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
{
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
{
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()); }
118 ExtensionFunction::ResponseValue result_
;
119 SendResponseCallback send_response_
;
122 class RespondLaterAction
: public ExtensionFunction::ResponseActionObject
{
124 ~RespondLaterAction() override
{}
126 void Execute() override
{}
129 // Used in implementation of ScopedUserGestureForTests.
130 class UserGestureForTests
{
132 static UserGestureForTests
* GetInstance();
134 // Returns true if there is at least one ScopedUserGestureForTests object
138 // These should be called when a ScopedUserGestureForTests object is
139 // created/destroyed respectively.
140 void IncrementCount();
141 void DecrementCount();
144 UserGestureForTests();
145 friend struct DefaultSingletonTraits
<UserGestureForTests
>;
147 base::Lock lock_
; // for protecting access to count_
152 UserGestureForTests
* UserGestureForTests::GetInstance() {
153 return Singleton
<UserGestureForTests
>::get();
156 UserGestureForTests::UserGestureForTests() : count_(0) {}
158 bool UserGestureForTests::HaveGesture() {
159 base::AutoLock
autolock(lock_
);
163 void UserGestureForTests::IncrementCount() {
164 base::AutoLock
autolock(lock_
);
168 void UserGestureForTests::DecrementCount() {
169 base::AutoLock
autolock(lock_
);
177 void ExtensionFunctionDeleteTraits::Destruct(const ExtensionFunction
* x
) {
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
{
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
) {
197 // content::WebContentsObserver:
198 void RenderViewDeleted(content::RenderViewHost
* render_view_host
) override
{
199 if (render_view_host
!= function_
->render_view_host())
202 function_
->SetRenderViewHost(NULL
);
204 void RenderFrameDeleted(
205 content::RenderFrameHost
* render_frame_host
) override
{
206 if (render_frame_host
!= function_
->render_frame_host())
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
);
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()
234 has_callback_(false),
235 include_incognito_(false),
236 user_gesture_(false),
238 histogram_value_(extensions::functions::UNKNOWN
),
240 source_context_type_(Feature::UNSPECIFIED_CONTEXT
) {
243 ExtensionFunction::~ExtensionFunction() {
246 UIThreadExtensionFunction
* ExtensionFunction::AsUIThreadExtensionFunction() {
250 IOThreadExtensionFunction
* ExtensionFunction::AsIOThreadExtensionFunction() {
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
;
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::SetResult(scoped_ptr
<base::Value
> result
) {
277 results_
.reset(new base::ListValue());
278 results_
->Append(result
.Pass());
281 void ExtensionFunction::SetResultList(scoped_ptr
<base::ListValue
> results
) {
282 results_
= results
.Pass();
285 const base::ListValue
* ExtensionFunction::GetResultList() const {
286 return results_
.get();
289 std::string
ExtensionFunction::GetError() const {
293 void ExtensionFunction::SetError(const std::string
& error
) {
297 bool ExtensionFunction::user_gesture() const {
298 return user_gesture_
|| UserGestureForTests::GetInstance()->HaveGesture();
301 ExtensionFunction::ResponseValue
ExtensionFunction::NoArguments() {
302 return ResponseValue(new ArgumentListResponseValue(
303 name(), "NoArguments", this, make_scoped_ptr(new base::ListValue())));
306 ExtensionFunction::ResponseValue
ExtensionFunction::OneArgument(
308 scoped_ptr
<base::ListValue
> args(new base::ListValue());
310 return ResponseValue(
311 new ArgumentListResponseValue(name(), "OneArgument", this, args
.Pass()));
314 ExtensionFunction::ResponseValue
ExtensionFunction::OneArgument(
315 scoped_ptr
<base::Value
> arg
) {
316 return OneArgument(arg
.release());
319 ExtensionFunction::ResponseValue
ExtensionFunction::TwoArguments(
322 scoped_ptr
<base::ListValue
> args(new base::ListValue());
325 return ResponseValue(
326 new ArgumentListResponseValue(name(), "TwoArguments", this, args
.Pass()));
329 ExtensionFunction::ResponseValue
ExtensionFunction::ArgumentList(
330 scoped_ptr
<base::ListValue
> args
) {
331 return ResponseValue(
332 new ArgumentListResponseValue(name(), "ArgumentList", this, args
.Pass()));
335 ExtensionFunction::ResponseValue
ExtensionFunction::Error(
336 const std::string
& error
) {
337 return ResponseValue(new ErrorResponseValue(this, error
));
340 ExtensionFunction::ResponseValue
ExtensionFunction::Error(
341 const std::string
& format
,
342 const std::string
& s1
) {
343 return ResponseValue(
344 new ErrorResponseValue(this, ErrorUtils::FormatErrorMessage(format
, s1
)));
347 ExtensionFunction::ResponseValue
ExtensionFunction::Error(
348 const std::string
& format
,
349 const std::string
& s1
,
350 const std::string
& s2
) {
351 return ResponseValue(new ErrorResponseValue(
352 this, ErrorUtils::FormatErrorMessage(format
, s1
, s2
)));
355 ExtensionFunction::ResponseValue
ExtensionFunction::Error(
356 const std::string
& format
,
357 const std::string
& s1
,
358 const std::string
& s2
,
359 const std::string
& s3
) {
360 return ResponseValue(new ErrorResponseValue(
361 this, ErrorUtils::FormatErrorMessage(format
, s1
, s2
, s3
)));
364 ExtensionFunction::ResponseValue
ExtensionFunction::ErrorWithArguments(
365 scoped_ptr
<base::ListValue
> args
,
366 const std::string
& error
) {
367 return ResponseValue(new ErrorWithArgumentsResponseValue(
368 name(), "ErrorWithArguments", this, args
.Pass(), error
));
371 ExtensionFunction::ResponseValue
ExtensionFunction::BadMessage() {
372 return ResponseValue(new BadMessageResponseValue(this));
375 ExtensionFunction::ResponseAction
ExtensionFunction::RespondNow(
376 ResponseValue result
) {
377 return ResponseAction(new RespondNowAction(
378 result
.Pass(), base::Bind(&ExtensionFunction::SendResponse
, this)));
381 ExtensionFunction::ResponseAction
ExtensionFunction::RespondLater() {
382 return ResponseAction(new RespondLaterAction());
386 ExtensionFunction::ResponseAction
ExtensionFunction::ValidationFailure(
387 ExtensionFunction
* function
) {
388 return function
->RespondNow(function
->BadMessage());
391 void ExtensionFunction::Respond(ResponseValue result
) {
392 SendResponse(result
->Apply());
395 bool ExtensionFunction::ShouldSkipQuotaLimiting() const {
399 bool ExtensionFunction::HasOptionalArgument(size_t index
) {
401 return args_
->Get(index
, &value
) && !value
->IsType(base::Value::TYPE_NULL
);
404 void ExtensionFunction::SendResponseImpl(bool success
) {
405 DCHECK(!response_callback_
.is_null());
407 ResponseType type
= success
? SUCCEEDED
: FAILED
;
410 LOG(ERROR
) << "Bad extension message " << name_
;
413 // If results were never set, we send an empty argument list.
415 results_
.reset(new base::ListValue());
417 response_callback_
.Run(type
, *results_
, GetError(), histogram_value());
420 void ExtensionFunction::OnRespondingLater(ResponseValue value
) {
421 SendResponse(value
->Apply());
424 UIThreadExtensionFunction::UIThreadExtensionFunction()
425 : render_view_host_(NULL
),
426 render_frame_host_(NULL
),
431 UIThreadExtensionFunction::~UIThreadExtensionFunction() {
432 if (dispatcher() && render_view_host())
433 dispatcher()->OnExtensionFunctionCompleted(extension());
436 UIThreadExtensionFunction
*
437 UIThreadExtensionFunction::AsUIThreadExtensionFunction() {
441 bool UIThreadExtensionFunction::OnMessageReceived(const IPC::Message
& message
) {
445 void UIThreadExtensionFunction::Destruct() const {
446 BrowserThread::DeleteOnUIThread::Destruct(this);
449 void UIThreadExtensionFunction::SetRenderViewHost(
450 RenderViewHost
* render_view_host
) {
451 DCHECK(!render_frame_host_
);
452 render_view_host_
= render_view_host
;
453 tracker_
.reset(render_view_host
? new RenderHostTracker(this) : NULL
);
456 void UIThreadExtensionFunction::SetRenderFrameHost(
457 content::RenderFrameHost
* render_frame_host
) {
458 DCHECK(!render_view_host_
);
459 render_frame_host_
= render_frame_host
;
460 tracker_
.reset(render_frame_host
? new RenderHostTracker(this) : NULL
);
463 content::WebContents
* UIThreadExtensionFunction::GetAssociatedWebContents() {
464 content::WebContents
* web_contents
= NULL
;
466 web_contents
= dispatcher()->delegate()->GetAssociatedWebContents();
471 content::WebContents
* UIThreadExtensionFunction::GetSenderWebContents() {
472 return render_view_host_
?
473 content::WebContents::FromRenderViewHost(render_view_host_
) : nullptr;
476 void UIThreadExtensionFunction::SendResponse(bool success
) {
478 delegate_
->OnSendResponse(this, success
, bad_message_
);
480 SendResponseImpl(success
);
482 if (!transferred_blob_uuids_
.empty()) {
483 DCHECK(!delegate_
) << "Blob transfer not supported with test delegate.";
484 GetIPCSender()->Send(
485 new ExtensionMsg_TransferBlobs(transferred_blob_uuids_
));
489 void UIThreadExtensionFunction::SetTransferredBlobUUIDs(
490 const std::vector
<std::string
>& blob_uuids
) {
491 DCHECK(transferred_blob_uuids_
.empty()); // Should only be called once.
492 transferred_blob_uuids_
= blob_uuids
;
495 void UIThreadExtensionFunction::WriteToConsole(
496 content::ConsoleMessageLevel level
,
497 const std::string
& message
) {
498 GetIPCSender()->Send(
499 new ExtensionMsg_AddMessageToConsole(GetRoutingID(), level
, message
));
502 IPC::Sender
* UIThreadExtensionFunction::GetIPCSender() {
503 if (render_view_host_
)
504 return render_view_host_
;
506 return render_frame_host_
;
509 int UIThreadExtensionFunction::GetRoutingID() {
510 if (render_view_host_
)
511 return render_view_host_
->GetRoutingID();
513 return render_frame_host_
->GetRoutingID();
516 IOThreadExtensionFunction::IOThreadExtensionFunction()
517 : routing_id_(MSG_ROUTING_NONE
) {
520 IOThreadExtensionFunction::~IOThreadExtensionFunction() {
523 IOThreadExtensionFunction
*
524 IOThreadExtensionFunction::AsIOThreadExtensionFunction() {
528 void IOThreadExtensionFunction::Destruct() const {
529 BrowserThread::DeleteOnIOThread::Destruct(this);
532 void IOThreadExtensionFunction::SendResponse(bool success
) {
533 SendResponseImpl(success
);
536 AsyncExtensionFunction::AsyncExtensionFunction() {
539 AsyncExtensionFunction::~AsyncExtensionFunction() {
542 ExtensionFunction::ScopedUserGestureForTests::ScopedUserGestureForTests() {
543 UserGestureForTests::GetInstance()->IncrementCount();
546 ExtensionFunction::ScopedUserGestureForTests::~ScopedUserGestureForTests() {
547 UserGestureForTests::GetInstance()->DecrementCount();
550 ExtensionFunction::ResponseAction
AsyncExtensionFunction::Run() {
551 return RunAsync() ? RespondLater() : RespondNow(Error(error_
));
555 bool AsyncExtensionFunction::ValidationFailure(
556 AsyncExtensionFunction
* function
) {
560 SyncExtensionFunction::SyncExtensionFunction() {
563 SyncExtensionFunction::~SyncExtensionFunction() {
566 ExtensionFunction::ResponseAction
SyncExtensionFunction::Run() {
567 return RespondNow(RunSync() ? ArgumentList(results_
.Pass()) : Error(error_
));
571 bool SyncExtensionFunction::ValidationFailure(SyncExtensionFunction
* function
) {
575 SyncIOThreadExtensionFunction::SyncIOThreadExtensionFunction() {
578 SyncIOThreadExtensionFunction::~SyncIOThreadExtensionFunction() {
581 ExtensionFunction::ResponseAction
SyncIOThreadExtensionFunction::Run() {
582 return RespondNow(RunSync() ? ArgumentList(results_
.Pass()) : Error(error_
));
586 bool SyncIOThreadExtensionFunction::ValidationFailure(
587 SyncIOThreadExtensionFunction
* function
) {