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 ErrorResponseValue
: public ExtensionFunction::ResponseValueObject
{
65 ErrorResponseValue(ExtensionFunction
* function
, const std::string
& error
) {
66 // It would be nice to DCHECK(!error.empty()) but too many legacy extension
67 // function implementations don't set error but signal failure.
68 function
->SetError(error
);
71 ~ErrorResponseValue() override
{}
73 bool Apply() override
{ return false; }
76 class BadMessageResponseValue
: public ExtensionFunction::ResponseValueObject
{
78 explicit BadMessageResponseValue(ExtensionFunction
* function
) {
79 function
->set_bad_message(true);
80 NOTREACHED() << function
->name() << ": bad message";
83 ~BadMessageResponseValue() override
{}
85 bool Apply() override
{ return false; }
88 class RespondNowAction
: public ExtensionFunction::ResponseActionObject
{
90 typedef base::Callback
<void(bool)> SendResponseCallback
;
91 RespondNowAction(ExtensionFunction::ResponseValue result
,
92 const SendResponseCallback
& send_response
)
93 : result_(result
.Pass()), send_response_(send_response
) {}
94 ~RespondNowAction() override
{}
96 void Execute() override
{ send_response_
.Run(result_
->Apply()); }
99 ExtensionFunction::ResponseValue result_
;
100 SendResponseCallback send_response_
;
103 class RespondLaterAction
: public ExtensionFunction::ResponseActionObject
{
105 ~RespondLaterAction() override
{}
107 void Execute() override
{}
110 // Used in implementation of ScopedUserGestureForTests.
111 class UserGestureForTests
{
113 static UserGestureForTests
* GetInstance();
115 // Returns true if there is at least one ScopedUserGestureForTests object
119 // These should be called when a ScopedUserGestureForTests object is
120 // created/destroyed respectively.
121 void IncrementCount();
122 void DecrementCount();
125 UserGestureForTests();
126 friend struct DefaultSingletonTraits
<UserGestureForTests
>;
128 base::Lock lock_
; // for protecting access to count_
133 UserGestureForTests
* UserGestureForTests::GetInstance() {
134 return Singleton
<UserGestureForTests
>::get();
137 UserGestureForTests::UserGestureForTests() : count_(0) {}
139 bool UserGestureForTests::HaveGesture() {
140 base::AutoLock
autolock(lock_
);
144 void UserGestureForTests::IncrementCount() {
145 base::AutoLock
autolock(lock_
);
149 void UserGestureForTests::DecrementCount() {
150 base::AutoLock
autolock(lock_
);
158 void ExtensionFunctionDeleteTraits::Destruct(const ExtensionFunction
* x
) {
162 // Helper class to track the lifetime of ExtensionFunction's RenderViewHost or
163 // RenderFrameHost pointer and NULL it out when it dies. It also allows us to
164 // filter IPC messages coming from the RenderViewHost/RenderFrameHost.
165 class UIThreadExtensionFunction::RenderHostTracker
166 : public content::WebContentsObserver
{
168 explicit RenderHostTracker(UIThreadExtensionFunction
* function
)
169 : content::WebContentsObserver(
170 function
->render_view_host() ?
171 WebContents::FromRenderViewHost(function
->render_view_host()) :
172 WebContents::FromRenderFrameHost(
173 function
->render_frame_host())),
174 function_(function
) {
178 // content::WebContentsObserver:
179 void RenderViewDeleted(content::RenderViewHost
* render_view_host
) override
{
180 if (render_view_host
!= function_
->render_view_host())
183 function_
->SetRenderViewHost(NULL
);
185 void RenderFrameDeleted(
186 content::RenderFrameHost
* render_frame_host
) override
{
187 if (render_frame_host
!= function_
->render_frame_host())
190 function_
->SetRenderFrameHost(NULL
);
193 bool OnMessageReceived(const IPC::Message
& message
,
194 content::RenderFrameHost
* render_frame_host
) override
{
195 DCHECK(render_frame_host
);
196 if (render_frame_host
== function_
->render_frame_host())
197 return function_
->OnMessageReceived(message
);
202 bool OnMessageReceived(const IPC::Message
& message
) override
{
203 return function_
->OnMessageReceived(message
);
206 UIThreadExtensionFunction
* function_
;
208 DISALLOW_COPY_AND_ASSIGN(RenderHostTracker
);
211 ExtensionFunction::ExtensionFunction()
214 has_callback_(false),
215 include_incognito_(false),
216 user_gesture_(false),
218 histogram_value_(extensions::functions::UNKNOWN
),
220 source_context_type_(Feature::UNSPECIFIED_CONTEXT
) {
223 ExtensionFunction::~ExtensionFunction() {
226 UIThreadExtensionFunction
* ExtensionFunction::AsUIThreadExtensionFunction() {
230 IOThreadExtensionFunction
* ExtensionFunction::AsIOThreadExtensionFunction() {
234 bool ExtensionFunction::HasPermission() {
235 Feature::Availability availability
=
236 ExtensionAPI::GetSharedInstance()->IsAvailable(
237 name_
, extension_
.get(), source_context_type_
, source_url());
238 return availability
.is_available();
241 void ExtensionFunction::OnQuotaExceeded(const std::string
& violation_error
) {
242 error_
= violation_error
;
246 void ExtensionFunction::SetArgs(const base::ListValue
* args
) {
247 DCHECK(!args_
.get()); // Should only be called once.
248 args_
.reset(args
->DeepCopy());
251 void ExtensionFunction::SetResult(base::Value
* result
) {
252 results_
.reset(new base::ListValue());
253 results_
->Append(result
);
256 void ExtensionFunction::SetResultList(scoped_ptr
<base::ListValue
> results
) {
257 results_
= results
.Pass();
260 const base::ListValue
* ExtensionFunction::GetResultList() const {
261 return results_
.get();
264 std::string
ExtensionFunction::GetError() const {
268 void ExtensionFunction::SetError(const std::string
& error
) {
272 bool ExtensionFunction::user_gesture() const {
273 return user_gesture_
|| UserGestureForTests::GetInstance()->HaveGesture();
276 ExtensionFunction::ResponseValue
ExtensionFunction::NoArguments() {
277 return ResponseValue(new ArgumentListResponseValue(
278 name(), "NoArguments", this, make_scoped_ptr(new base::ListValue())));
281 ExtensionFunction::ResponseValue
ExtensionFunction::OneArgument(
283 scoped_ptr
<base::ListValue
> args(new base::ListValue());
285 return ResponseValue(
286 new ArgumentListResponseValue(name(), "OneArgument", this, args
.Pass()));
289 ExtensionFunction::ResponseValue
ExtensionFunction::TwoArguments(
292 scoped_ptr
<base::ListValue
> args(new base::ListValue());
295 return ResponseValue(
296 new ArgumentListResponseValue(name(), "TwoArguments", this, args
.Pass()));
299 ExtensionFunction::ResponseValue
ExtensionFunction::ArgumentList(
300 scoped_ptr
<base::ListValue
> args
) {
301 return ResponseValue(
302 new ArgumentListResponseValue(name(), "ArgumentList", this, args
.Pass()));
305 ExtensionFunction::ResponseValue
ExtensionFunction::Error(
306 const std::string
& error
) {
307 return ResponseValue(new ErrorResponseValue(this, error
));
310 ExtensionFunction::ResponseValue
ExtensionFunction::Error(
311 const std::string
& format
,
312 const std::string
& s1
) {
313 return ResponseValue(
314 new ErrorResponseValue(this, ErrorUtils::FormatErrorMessage(format
, s1
)));
317 ExtensionFunction::ResponseValue
ExtensionFunction::Error(
318 const std::string
& format
,
319 const std::string
& s1
,
320 const std::string
& s2
) {
321 return ResponseValue(new ErrorResponseValue(
322 this, ErrorUtils::FormatErrorMessage(format
, s1
, s2
)));
325 ExtensionFunction::ResponseValue
ExtensionFunction::Error(
326 const std::string
& format
,
327 const std::string
& s1
,
328 const std::string
& s2
,
329 const std::string
& s3
) {
330 return ResponseValue(new ErrorResponseValue(
331 this, ErrorUtils::FormatErrorMessage(format
, s1
, s2
, s3
)));
334 ExtensionFunction::ResponseValue
ExtensionFunction::BadMessage() {
335 return ResponseValue(new BadMessageResponseValue(this));
338 ExtensionFunction::ResponseAction
ExtensionFunction::RespondNow(
339 ResponseValue result
) {
340 return ResponseAction(new RespondNowAction(
341 result
.Pass(), base::Bind(&ExtensionFunction::SendResponse
, this)));
344 ExtensionFunction::ResponseAction
ExtensionFunction::RespondLater() {
345 return ResponseAction(new RespondLaterAction());
349 ExtensionFunction::ResponseAction
ExtensionFunction::ValidationFailure(
350 ExtensionFunction
* function
) {
351 return function
->RespondNow(function
->BadMessage());
354 void ExtensionFunction::Respond(ResponseValue result
) {
355 SendResponse(result
->Apply());
358 bool ExtensionFunction::ShouldSkipQuotaLimiting() const {
362 bool ExtensionFunction::HasOptionalArgument(size_t index
) {
364 return args_
->Get(index
, &value
) && !value
->IsType(base::Value::TYPE_NULL
);
367 void ExtensionFunction::SendResponseImpl(bool success
) {
368 DCHECK(!response_callback_
.is_null());
370 ResponseType type
= success
? SUCCEEDED
: FAILED
;
373 LOG(ERROR
) << "Bad extension message " << name_
;
376 // If results were never set, we send an empty argument list.
378 results_
.reset(new base::ListValue());
380 response_callback_
.Run(type
, *results_
, GetError());
383 void ExtensionFunction::OnRespondingLater(ResponseValue value
) {
384 SendResponse(value
->Apply());
387 UIThreadExtensionFunction::UIThreadExtensionFunction()
388 : render_view_host_(NULL
),
389 render_frame_host_(NULL
),
394 UIThreadExtensionFunction::~UIThreadExtensionFunction() {
395 if (dispatcher() && render_view_host())
396 dispatcher()->OnExtensionFunctionCompleted(extension());
399 UIThreadExtensionFunction
*
400 UIThreadExtensionFunction::AsUIThreadExtensionFunction() {
404 bool UIThreadExtensionFunction::OnMessageReceived(const IPC::Message
& message
) {
408 void UIThreadExtensionFunction::Destruct() const {
409 BrowserThread::DeleteOnUIThread::Destruct(this);
412 void UIThreadExtensionFunction::SetRenderViewHost(
413 RenderViewHost
* render_view_host
) {
414 DCHECK(!render_frame_host_
);
415 render_view_host_
= render_view_host
;
416 tracker_
.reset(render_view_host
? new RenderHostTracker(this) : NULL
);
419 void UIThreadExtensionFunction::SetRenderFrameHost(
420 content::RenderFrameHost
* render_frame_host
) {
421 DCHECK(!render_view_host_
);
422 render_frame_host_
= render_frame_host
;
423 tracker_
.reset(render_frame_host
? new RenderHostTracker(this) : NULL
);
426 content::WebContents
* UIThreadExtensionFunction::GetAssociatedWebContents() {
427 content::WebContents
* web_contents
= NULL
;
429 web_contents
= dispatcher()->delegate()->GetAssociatedWebContents();
434 void UIThreadExtensionFunction::SendResponse(bool success
) {
436 delegate_
->OnSendResponse(this, success
, bad_message_
);
438 SendResponseImpl(success
);
440 if (!transferred_blob_uuids_
.empty()) {
441 DCHECK(!delegate_
) << "Blob transfer not supported with test delegate.";
442 GetIPCSender()->Send(
443 new ExtensionMsg_TransferBlobs(transferred_blob_uuids_
));
447 void UIThreadExtensionFunction::SetTransferredBlobUUIDs(
448 const std::vector
<std::string
>& blob_uuids
) {
449 DCHECK(transferred_blob_uuids_
.empty()); // Should only be called once.
450 transferred_blob_uuids_
= blob_uuids
;
453 void UIThreadExtensionFunction::WriteToConsole(
454 content::ConsoleMessageLevel level
,
455 const std::string
& message
) {
456 GetIPCSender()->Send(
457 new ExtensionMsg_AddMessageToConsole(GetRoutingID(), level
, message
));
460 IPC::Sender
* UIThreadExtensionFunction::GetIPCSender() {
461 if (render_view_host_
)
462 return render_view_host_
;
464 return render_frame_host_
;
467 int UIThreadExtensionFunction::GetRoutingID() {
468 if (render_view_host_
)
469 return render_view_host_
->GetRoutingID();
471 return render_frame_host_
->GetRoutingID();
474 IOThreadExtensionFunction::IOThreadExtensionFunction()
475 : routing_id_(MSG_ROUTING_NONE
) {
478 IOThreadExtensionFunction::~IOThreadExtensionFunction() {
481 IOThreadExtensionFunction
*
482 IOThreadExtensionFunction::AsIOThreadExtensionFunction() {
486 void IOThreadExtensionFunction::Destruct() const {
487 BrowserThread::DeleteOnIOThread::Destruct(this);
490 void IOThreadExtensionFunction::SendResponse(bool success
) {
491 SendResponseImpl(success
);
494 AsyncExtensionFunction::AsyncExtensionFunction() {
497 AsyncExtensionFunction::~AsyncExtensionFunction() {
500 ExtensionFunction::ScopedUserGestureForTests::ScopedUserGestureForTests() {
501 UserGestureForTests::GetInstance()->IncrementCount();
504 ExtensionFunction::ScopedUserGestureForTests::~ScopedUserGestureForTests() {
505 UserGestureForTests::GetInstance()->DecrementCount();
508 ExtensionFunction::ResponseAction
AsyncExtensionFunction::Run() {
509 return RunAsync() ? RespondLater() : RespondNow(Error(error_
));
513 bool AsyncExtensionFunction::ValidationFailure(
514 AsyncExtensionFunction
* function
) {
518 SyncExtensionFunction::SyncExtensionFunction() {
521 SyncExtensionFunction::~SyncExtensionFunction() {
524 ExtensionFunction::ResponseAction
SyncExtensionFunction::Run() {
525 return RespondNow(RunSync() ? ArgumentList(results_
.Pass()) : Error(error_
));
529 bool SyncExtensionFunction::ValidationFailure(SyncExtensionFunction
* function
) {
533 SyncIOThreadExtensionFunction::SyncIOThreadExtensionFunction() {
536 SyncIOThreadExtensionFunction::~SyncIOThreadExtensionFunction() {
539 ExtensionFunction::ResponseAction
SyncIOThreadExtensionFunction::Run() {
540 return RespondNow(RunSync() ? ArgumentList(results_
.Pass()) : Error(error_
));
544 bool SyncIOThreadExtensionFunction::ValidationFailure(
545 SyncIOThreadExtensionFunction
* function
) {