Revert of Fix missing GN dependencies. (patchset #4 id:60001 of https://codereview...
[chromium-blink-merge.git] / extensions / browser / extension_function.cc
blob46e3ba136953c3f02df46ed287780e1c6b712e36
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::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 {
290 return error_;
293 void ExtensionFunction::SetError(const std::string& error) {
294 error_ = 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(
307 base::Value* arg) {
308 scoped_ptr<base::ListValue> args(new base::ListValue());
309 args->Append(arg);
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(
320 base::Value* arg1,
321 base::Value* arg2) {
322 scoped_ptr<base::ListValue> args(new base::ListValue());
323 args->Append(arg1);
324 args->Append(arg2);
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());
385 // static
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 {
396 return false;
399 bool ExtensionFunction::HasOptionalArgument(size_t index) {
400 base::Value* value;
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;
408 if (bad_message_) {
409 type = BAD_MESSAGE;
410 LOG(ERROR) << "Bad extension message " << name_;
413 // If results were never set, we send an empty argument list.
414 if (!results_)
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),
427 context_(NULL),
428 delegate_(NULL) {
431 UIThreadExtensionFunction::~UIThreadExtensionFunction() {
432 if (dispatcher() && render_view_host())
433 dispatcher()->OnExtensionFunctionCompleted(extension());
436 UIThreadExtensionFunction*
437 UIThreadExtensionFunction::AsUIThreadExtensionFunction() {
438 return this;
441 bool UIThreadExtensionFunction::OnMessageReceived(const IPC::Message& message) {
442 return false;
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;
465 if (dispatcher())
466 web_contents = dispatcher()->delegate()->GetAssociatedWebContents();
468 return web_contents;
471 content::WebContents* UIThreadExtensionFunction::GetSenderWebContents() {
472 return render_view_host_ ?
473 content::WebContents::FromRenderViewHost(render_view_host_) : nullptr;
476 void UIThreadExtensionFunction::SendResponse(bool success) {
477 if (delegate_)
478 delegate_->OnSendResponse(this, success, bad_message_);
479 else
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_;
505 else
506 return render_frame_host_;
509 int UIThreadExtensionFunction::GetRoutingID() {
510 if (render_view_host_)
511 return render_view_host_->GetRoutingID();
512 else
513 return render_frame_host_->GetRoutingID();
516 IOThreadExtensionFunction::IOThreadExtensionFunction()
517 : routing_id_(MSG_ROUTING_NONE) {
520 IOThreadExtensionFunction::~IOThreadExtensionFunction() {
523 IOThreadExtensionFunction*
524 IOThreadExtensionFunction::AsIOThreadExtensionFunction() {
525 return this;
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_));
554 // static
555 bool AsyncExtensionFunction::ValidationFailure(
556 AsyncExtensionFunction* function) {
557 return false;
560 SyncExtensionFunction::SyncExtensionFunction() {
563 SyncExtensionFunction::~SyncExtensionFunction() {
566 ExtensionFunction::ResponseAction SyncExtensionFunction::Run() {
567 return RespondNow(RunSync() ? ArgumentList(results_.Pass()) : Error(error_));
570 // static
571 bool SyncExtensionFunction::ValidationFailure(SyncExtensionFunction* function) {
572 return false;
575 SyncIOThreadExtensionFunction::SyncIOThreadExtensionFunction() {
578 SyncIOThreadExtensionFunction::~SyncIOThreadExtensionFunction() {
581 ExtensionFunction::ResponseAction SyncIOThreadExtensionFunction::Run() {
582 return RespondNow(RunSync() ? ArgumentList(results_.Pass()) : Error(error_));
585 // static
586 bool SyncIOThreadExtensionFunction::ValidationFailure(
587 SyncIOThreadExtensionFunction* function) {
588 return false;