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
),
241 source_process_id_(-1) {
244 ExtensionFunction::~ExtensionFunction() {
247 UIThreadExtensionFunction
* ExtensionFunction::AsUIThreadExtensionFunction() {
251 IOThreadExtensionFunction
* ExtensionFunction::AsIOThreadExtensionFunction() {
255 bool ExtensionFunction::HasPermission() {
256 Feature::Availability availability
=
257 ExtensionAPI::GetSharedInstance()->IsAvailable(
258 name_
, extension_
.get(), source_context_type_
, source_url());
259 return availability
.is_available();
262 void ExtensionFunction::OnQuotaExceeded(const std::string
& violation_error
) {
263 error_
= violation_error
;
267 void ExtensionFunction::SetArgs(const base::ListValue
* args
) {
268 DCHECK(!args_
.get()); // Should only be called once.
269 args_
.reset(args
->DeepCopy());
272 void ExtensionFunction::SetResult(base::Value
* result
) {
273 results_
.reset(new base::ListValue());
274 results_
->Append(result
);
277 void ExtensionFunction::SetResult(scoped_ptr
<base::Value
> result
) {
278 results_
.reset(new base::ListValue());
279 results_
->Append(result
.Pass());
282 void ExtensionFunction::SetResultList(scoped_ptr
<base::ListValue
> results
) {
283 results_
= results
.Pass();
286 const base::ListValue
* ExtensionFunction::GetResultList() const {
287 return results_
.get();
290 std::string
ExtensionFunction::GetError() const {
294 void ExtensionFunction::SetError(const std::string
& error
) {
298 bool ExtensionFunction::user_gesture() const {
299 return user_gesture_
|| UserGestureForTests::GetInstance()->HaveGesture();
302 ExtensionFunction::ResponseValue
ExtensionFunction::NoArguments() {
303 return ResponseValue(new ArgumentListResponseValue(
304 name(), "NoArguments", this, make_scoped_ptr(new base::ListValue())));
307 ExtensionFunction::ResponseValue
ExtensionFunction::OneArgument(
309 scoped_ptr
<base::ListValue
> args(new base::ListValue());
311 return ResponseValue(
312 new ArgumentListResponseValue(name(), "OneArgument", this, args
.Pass()));
315 ExtensionFunction::ResponseValue
ExtensionFunction::OneArgument(
316 scoped_ptr
<base::Value
> arg
) {
317 return OneArgument(arg
.release());
320 ExtensionFunction::ResponseValue
ExtensionFunction::TwoArguments(
323 scoped_ptr
<base::ListValue
> args(new base::ListValue());
326 return ResponseValue(
327 new ArgumentListResponseValue(name(), "TwoArguments", this, args
.Pass()));
330 ExtensionFunction::ResponseValue
ExtensionFunction::ArgumentList(
331 scoped_ptr
<base::ListValue
> args
) {
332 return ResponseValue(
333 new ArgumentListResponseValue(name(), "ArgumentList", this, args
.Pass()));
336 ExtensionFunction::ResponseValue
ExtensionFunction::Error(
337 const std::string
& error
) {
338 return ResponseValue(new ErrorResponseValue(this, error
));
341 ExtensionFunction::ResponseValue
ExtensionFunction::Error(
342 const std::string
& format
,
343 const std::string
& s1
) {
344 return ResponseValue(
345 new ErrorResponseValue(this, ErrorUtils::FormatErrorMessage(format
, s1
)));
348 ExtensionFunction::ResponseValue
ExtensionFunction::Error(
349 const std::string
& format
,
350 const std::string
& s1
,
351 const std::string
& s2
) {
352 return ResponseValue(new ErrorResponseValue(
353 this, ErrorUtils::FormatErrorMessage(format
, s1
, s2
)));
356 ExtensionFunction::ResponseValue
ExtensionFunction::Error(
357 const std::string
& format
,
358 const std::string
& s1
,
359 const std::string
& s2
,
360 const std::string
& s3
) {
361 return ResponseValue(new ErrorResponseValue(
362 this, ErrorUtils::FormatErrorMessage(format
, s1
, s2
, s3
)));
365 ExtensionFunction::ResponseValue
ExtensionFunction::ErrorWithArguments(
366 scoped_ptr
<base::ListValue
> args
,
367 const std::string
& error
) {
368 return ResponseValue(new ErrorWithArgumentsResponseValue(
369 name(), "ErrorWithArguments", this, args
.Pass(), error
));
372 ExtensionFunction::ResponseValue
ExtensionFunction::BadMessage() {
373 return ResponseValue(new BadMessageResponseValue(this));
376 ExtensionFunction::ResponseAction
ExtensionFunction::RespondNow(
377 ResponseValue result
) {
378 return ResponseAction(new RespondNowAction(
379 result
.Pass(), base::Bind(&ExtensionFunction::SendResponse
, this)));
382 ExtensionFunction::ResponseAction
ExtensionFunction::RespondLater() {
383 return ResponseAction(new RespondLaterAction());
387 ExtensionFunction::ResponseAction
ExtensionFunction::ValidationFailure(
388 ExtensionFunction
* function
) {
389 return function
->RespondNow(function
->BadMessage());
392 void ExtensionFunction::Respond(ResponseValue result
) {
393 SendResponse(result
->Apply());
396 bool ExtensionFunction::ShouldSkipQuotaLimiting() const {
400 bool ExtensionFunction::HasOptionalArgument(size_t index
) {
402 return args_
->Get(index
, &value
) && !value
->IsType(base::Value::TYPE_NULL
);
405 void ExtensionFunction::SendResponseImpl(bool success
) {
406 DCHECK(!response_callback_
.is_null());
408 ResponseType type
= success
? SUCCEEDED
: FAILED
;
411 LOG(ERROR
) << "Bad extension message " << name_
;
414 // If results were never set, we send an empty argument list.
416 results_
.reset(new base::ListValue());
418 response_callback_
.Run(type
, *results_
, GetError(), histogram_value());
421 void ExtensionFunction::OnRespondingLater(ResponseValue value
) {
422 SendResponse(value
->Apply());
425 UIThreadExtensionFunction::UIThreadExtensionFunction()
426 : render_view_host_(NULL
),
427 render_frame_host_(NULL
),
432 UIThreadExtensionFunction::~UIThreadExtensionFunction() {
433 if (dispatcher() && render_view_host())
434 dispatcher()->OnExtensionFunctionCompleted(extension());
437 UIThreadExtensionFunction
*
438 UIThreadExtensionFunction::AsUIThreadExtensionFunction() {
442 bool UIThreadExtensionFunction::OnMessageReceived(const IPC::Message
& message
) {
446 void UIThreadExtensionFunction::Destruct() const {
447 BrowserThread::DeleteOnUIThread::Destruct(this);
450 void UIThreadExtensionFunction::SetRenderViewHost(
451 RenderViewHost
* render_view_host
) {
452 DCHECK(!render_frame_host_
);
453 render_view_host_
= render_view_host
;
454 tracker_
.reset(render_view_host
? new RenderHostTracker(this) : NULL
);
457 void UIThreadExtensionFunction::SetRenderFrameHost(
458 content::RenderFrameHost
* render_frame_host
) {
459 DCHECK(!render_view_host_
);
460 render_frame_host_
= render_frame_host
;
461 tracker_
.reset(render_frame_host
? new RenderHostTracker(this) : NULL
);
464 content::WebContents
* UIThreadExtensionFunction::GetAssociatedWebContents() {
465 content::WebContents
* web_contents
= NULL
;
467 web_contents
= dispatcher()->GetAssociatedWebContents();
472 content::WebContents
* UIThreadExtensionFunction::GetSenderWebContents() {
473 return render_view_host_
?
474 content::WebContents::FromRenderViewHost(render_view_host_
) : nullptr;
477 void UIThreadExtensionFunction::SendResponse(bool success
) {
479 delegate_
->OnSendResponse(this, success
, bad_message_
);
481 SendResponseImpl(success
);
483 if (!transferred_blob_uuids_
.empty()) {
484 DCHECK(!delegate_
) << "Blob transfer not supported with test delegate.";
485 GetIPCSender()->Send(
486 new ExtensionMsg_TransferBlobs(transferred_blob_uuids_
));
490 void UIThreadExtensionFunction::SetTransferredBlobUUIDs(
491 const std::vector
<std::string
>& blob_uuids
) {
492 DCHECK(transferred_blob_uuids_
.empty()); // Should only be called once.
493 transferred_blob_uuids_
= blob_uuids
;
496 void UIThreadExtensionFunction::WriteToConsole(
497 content::ConsoleMessageLevel level
,
498 const std::string
& message
) {
499 GetIPCSender()->Send(
500 new ExtensionMsg_AddMessageToConsole(GetRoutingID(), level
, message
));
503 IPC::Sender
* UIThreadExtensionFunction::GetIPCSender() {
504 if (render_view_host_
)
505 return render_view_host_
;
507 return render_frame_host_
;
510 int UIThreadExtensionFunction::GetRoutingID() {
511 if (render_view_host_
)
512 return render_view_host_
->GetRoutingID();
514 return render_frame_host_
->GetRoutingID();
517 IOThreadExtensionFunction::IOThreadExtensionFunction()
518 : routing_id_(MSG_ROUTING_NONE
) {
521 IOThreadExtensionFunction::~IOThreadExtensionFunction() {
524 IOThreadExtensionFunction
*
525 IOThreadExtensionFunction::AsIOThreadExtensionFunction() {
529 void IOThreadExtensionFunction::Destruct() const {
530 BrowserThread::DeleteOnIOThread::Destruct(this);
533 void IOThreadExtensionFunction::SendResponse(bool success
) {
534 SendResponseImpl(success
);
537 AsyncExtensionFunction::AsyncExtensionFunction() {
540 AsyncExtensionFunction::~AsyncExtensionFunction() {
543 ExtensionFunction::ScopedUserGestureForTests::ScopedUserGestureForTests() {
544 UserGestureForTests::GetInstance()->IncrementCount();
547 ExtensionFunction::ScopedUserGestureForTests::~ScopedUserGestureForTests() {
548 UserGestureForTests::GetInstance()->DecrementCount();
551 ExtensionFunction::ResponseAction
AsyncExtensionFunction::Run() {
552 return RunAsync() ? RespondLater() : RespondNow(Error(error_
));
556 bool AsyncExtensionFunction::ValidationFailure(
557 AsyncExtensionFunction
* function
) {
561 SyncExtensionFunction::SyncExtensionFunction() {
564 SyncExtensionFunction::~SyncExtensionFunction() {
567 ExtensionFunction::ResponseAction
SyncExtensionFunction::Run() {
568 return RespondNow(RunSync() ? ArgumentList(results_
.Pass()) : Error(error_
));
572 bool SyncExtensionFunction::ValidationFailure(SyncExtensionFunction
* function
) {
576 SyncIOThreadExtensionFunction::SyncIOThreadExtensionFunction() {
579 SyncIOThreadExtensionFunction::~SyncIOThreadExtensionFunction() {
582 ExtensionFunction::ResponseAction
SyncIOThreadExtensionFunction::Run() {
583 return RespondNow(RunSync() ? ArgumentList(results_
.Pass()) : Error(error_
));
587 bool SyncIOThreadExtensionFunction::ValidationFailure(
588 SyncIOThreadExtensionFunction
* function
) {