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 #ifndef EXTENSIONS_BROWSER_EXTENSION_FUNCTION_H_
6 #define EXTENSIONS_BROWSER_EXTENSION_FUNCTION_H_
11 #include "base/callback.h"
12 #include "base/compiler_specific.h"
13 #include "base/memory/ref_counted.h"
14 #include "base/memory/scoped_ptr.h"
15 #include "base/memory/weak_ptr.h"
16 #include "base/process/process.h"
17 #include "base/sequenced_task_runner_helpers.h"
18 #include "content/public/browser/browser_thread.h"
19 #include "content/public/common/console_message_level.h"
20 #include "extensions/browser/extension_function_histogram_value.h"
21 #include "extensions/browser/info_map.h"
22 #include "extensions/common/extension.h"
23 #include "extensions/common/features/feature.h"
24 #include "ipc/ipc_message.h"
26 class ExtensionFunction
;
27 class UIThreadExtensionFunction
;
28 class IOThreadExtensionFunction
;
37 class RenderFrameHost
;
42 namespace extensions
{
43 class ExtensionFunctionDispatcher
;
44 class IOThreadExtensionMessageFilter
;
45 class QuotaLimitHeuristic
;
53 #define EXTENSION_FUNCTION_VALIDATE(test) \
56 this->bad_message_ = true; \
57 return ValidationFailure(this); \
61 #define EXTENSION_FUNCTION_VALIDATE(test) CHECK(test)
64 #define EXTENSION_FUNCTION_ERROR(error) \
67 this->bad_message_ = true; \
68 return ValidationFailure(this); \
71 // Declares a callable extension function with the given |name|. You must also
72 // supply a unique |histogramvalue| used for histograms of extension function
73 // invocation (add new ones at the end of the enum in
74 // extension_function_histogram_value.h).
75 #define DECLARE_EXTENSION_FUNCTION(name, histogramvalue) \
76 public: static const char* function_name() { return name; } \
77 public: static extensions::functions::HistogramValue histogram_value() \
78 { return extensions::functions::histogramvalue; }
80 // Traits that describe how ExtensionFunction should be deleted. This just calls
81 // the virtual "Destruct" method on ExtensionFunction, allowing derived classes
82 // to override the behavior.
83 struct ExtensionFunctionDeleteTraits
{
85 static void Destruct(const ExtensionFunction
* x
);
88 // Abstract base class for extension functions the ExtensionFunctionDispatcher
89 // knows how to dispatch to.
90 class ExtensionFunction
91 : public base::RefCountedThreadSafe
<ExtensionFunction
,
92 ExtensionFunctionDeleteTraits
> {
95 // The function has succeeded.
97 // The function has failed.
99 // The input message is malformed.
103 using ResponseCallback
= base::Callback
<void(
105 const base::ListValue
& results
,
106 const std::string
& error
,
107 extensions::functions::HistogramValue histogram_value
)>;
111 virtual UIThreadExtensionFunction
* AsUIThreadExtensionFunction();
112 virtual IOThreadExtensionFunction
* AsIOThreadExtensionFunction();
114 // Returns true if the function has permission to run.
116 // The default implementation is to check the Extension's permissions against
117 // what this function requires to run, but some APIs may require finer
118 // grained control, such as tabs.executeScript being allowed for active tabs.
120 // This will be run after the function has been set up but before Run().
121 virtual bool HasPermission();
123 // The result of a function call.
125 // Use NoArguments(), OneArgument(), ArgumentList(), or Error()
126 // rather than this class directly.
127 class ResponseValueObject
{
129 virtual ~ResponseValueObject() {}
131 // Returns true for success, false for failure.
132 virtual bool Apply() = 0;
134 typedef scoped_ptr
<ResponseValueObject
> ResponseValue
;
136 // The action to use when returning from RunAsync.
138 // Use RespondNow() or RespondLater() rather than this class directly.
139 class ResponseActionObject
{
141 virtual ~ResponseActionObject() {}
143 virtual void Execute() = 0;
145 typedef scoped_ptr
<ResponseActionObject
> ResponseAction
;
147 // Helper class for tests to force all ExtensionFunction::user_gesture()
148 // calls to return true as long as at least one instance of this class
150 class ScopedUserGestureForTests
{
152 ScopedUserGestureForTests();
153 ~ScopedUserGestureForTests();
156 // Runs the function and returns the action to take when the caller is ready
159 // Typical return values might be:
160 // * RespondNow(NoArguments())
161 // * RespondNow(OneArgument(42))
162 // * RespondNow(ArgumentList(my_result.ToValue()))
163 // * RespondNow(Error("Warp core breach"))
164 // * RespondNow(Error("Warp core breach on *", GetURL()))
165 // * RespondLater(), then later,
166 // * Respond(NoArguments())
170 // Callers must call Execute() on the return ResponseAction at some point,
173 // SyncExtensionFunction and AsyncExtensionFunction implement this in terms
174 // of SyncExtensionFunction::RunSync and AsyncExtensionFunction::RunAsync,
175 // but this is deprecated. ExtensionFunction implementations are encouraged
176 // to just implement Run.
177 virtual ResponseAction
Run() WARN_UNUSED_RESULT
= 0;
179 // Gets whether quota should be applied to this individual function
180 // invocation. This is different to GetQuotaLimitHeuristics which is only
181 // invoked once and then cached.
183 // Returns false by default.
184 virtual bool ShouldSkipQuotaLimiting() const;
186 // Optionally adds one or multiple QuotaLimitHeuristic instances suitable for
187 // this function to |heuristics|. The ownership of the new QuotaLimitHeuristic
188 // instances is passed to the owner of |heuristics|.
189 // No quota limiting by default.
191 // Only called once per lifetime of the QuotaService.
192 virtual void GetQuotaLimitHeuristics(
193 extensions::QuotaLimitHeuristics
* heuristics
) const {}
195 // Called when the quota limit has been exceeded. The default implementation
197 virtual void OnQuotaExceeded(const std::string
& violation_error
);
199 // Specifies the raw arguments to the function, as a JSON value.
200 virtual void SetArgs(const base::ListValue
* args
);
202 // Sets a single Value as the results of the function.
203 void SetResult(scoped_ptr
<base::Value
> result
);
204 // As above, but deprecated. TODO(estade): remove.
205 void SetResult(base::Value
* result
);
207 // Sets multiple Values as the results of the function.
208 void SetResultList(scoped_ptr
<base::ListValue
> results
);
210 // Retrieves the results of the function as a ListValue.
211 const base::ListValue
* GetResultList() const;
213 // Retrieves any error string from the function.
214 virtual std::string
GetError() const;
216 // Sets the function's error string.
217 virtual void SetError(const std::string
& error
);
219 // Sets the function's bad message state.
220 void set_bad_message(bool bad_message
) { bad_message_
= bad_message
; }
222 // Specifies the name of the function. A long-lived string (such as a string
223 // literal) must be provided.
224 void set_name(const char* name
) { name_
= name
; }
225 const char* name() const { return name_
; }
227 void set_profile_id(void* profile_id
) { profile_id_
= profile_id
; }
228 void* profile_id() const { return profile_id_
; }
231 const scoped_refptr
<const extensions::Extension
>& extension
) {
232 extension_
= extension
;
234 const extensions::Extension
* extension() const { return extension_
.get(); }
235 const std::string
& extension_id() const {
237 << "extension_id() called without an Extension. If " << name()
238 << " is allowed to be called without any Extension then you should "
239 << "check extension() first. If not, there is a bug in the Extension "
240 << "platform, so page somebody in extensions/OWNERS";
241 return extension_
->id();
244 void set_request_id(int request_id
) { request_id_
= request_id
; }
245 int request_id() { return request_id_
; }
247 void set_source_url(const GURL
& source_url
) { source_url_
= source_url
; }
248 const GURL
& source_url() { return source_url_
; }
250 void set_has_callback(bool has_callback
) { has_callback_
= has_callback
; }
251 bool has_callback() { return has_callback_
; }
253 void set_include_incognito(bool include
) { include_incognito_
= include
; }
254 bool include_incognito() const { return include_incognito_
; }
256 // Note: consider using ScopedUserGestureForTests instead of calling
257 // set_user_gesture directly.
258 void set_user_gesture(bool user_gesture
) { user_gesture_
= user_gesture
; }
259 bool user_gesture() const;
261 void set_histogram_value(
262 extensions::functions::HistogramValue histogram_value
) {
263 histogram_value_
= histogram_value
; }
264 extensions::functions::HistogramValue
histogram_value() const {
265 return histogram_value_
; }
267 void set_response_callback(const ResponseCallback
& callback
) {
268 response_callback_
= callback
;
271 void set_source_tab_id(int source_tab_id
) { source_tab_id_
= source_tab_id
; }
272 int source_tab_id() const { return source_tab_id_
; }
274 void set_source_context_type(extensions::Feature::Context type
) {
275 source_context_type_
= type
;
277 extensions::Feature::Context
source_context_type() const {
278 return source_context_type_
;
281 void set_source_process_id(int source_process_id
) {
282 source_process_id_
= source_process_id
;
284 int source_process_id() const {
285 return source_process_id_
;
289 friend struct ExtensionFunctionDeleteTraits
;
293 // Success, no arguments to pass to caller.
294 ResponseValue
NoArguments();
295 // Success, a single argument |arg| to pass to caller. TAKES OWNERSHIP - a
296 // raw pointer for convenience, since callers usually construct the argument
298 ResponseValue
OneArgument(base::Value
* arg
);
299 // Success, a single argument |arg| to pass to caller.
300 ResponseValue
OneArgument(scoped_ptr
<base::Value
> arg
);
301 // Success, two arguments |arg1| and |arg2| to pass to caller. TAKES
302 // OWNERSHIP - raw pointers for convenience, since callers usually construct
303 // the argument to this by hand. Note that use of this function may imply you
304 // should be using the generated Result struct and ArgumentList.
305 ResponseValue
TwoArguments(base::Value
* arg1
, base::Value
* arg2
);
306 // Success, a list of arguments |results| to pass to caller. TAKES OWNERSHIP
307 // - a scoped_ptr<> for convenience, since callers usually get this from the
308 // result of a Create(...) call on the generated Results struct, for example,
309 // alarms::Get::Results::Create(alarm).
310 ResponseValue
ArgumentList(scoped_ptr
<base::ListValue
> results
);
311 // Error. chrome.runtime.lastError.message will be set to |error|.
312 ResponseValue
Error(const std::string
& error
);
313 // Error with formatting. Args are processed using
314 // ErrorUtils::FormatErrorMessage, that is, each occurence of * is replaced
315 // by the corresponding |s*|:
316 // Error("Error in *: *", "foo", "bar") <--> Error("Error in foo: bar").
317 ResponseValue
Error(const std::string
& format
, const std::string
& s1
);
318 ResponseValue
Error(const std::string
& format
,
319 const std::string
& s1
,
320 const std::string
& s2
);
321 ResponseValue
Error(const std::string
& format
,
322 const std::string
& s1
,
323 const std::string
& s2
,
324 const std::string
& s3
);
325 // Error with a list of arguments |args| to pass to caller. TAKES OWNERSHIP.
326 // Using this ResponseValue indicates something is wrong with the API.
327 // It shouldn't be possible to have both an error *and* some arguments.
328 // Some legacy APIs do rely on it though, like webstorePrivate.
329 ResponseValue
ErrorWithArguments(scoped_ptr
<base::ListValue
> args
,
330 const std::string
& error
);
331 // Bad message. A ResponseValue equivalent to EXTENSION_FUNCTION_VALIDATE(),
332 // so this will actually kill the renderer and not respond at all.
333 ResponseValue
BadMessage();
337 // These are exclusively used as return values from Run(). Call Respond(...)
338 // to respond at any other time - but as described below, only after Run()
339 // has already executed, and only if it returned RespondLater().
341 // Respond to the extension immediately with |result|.
342 ResponseAction
RespondNow(ResponseValue result
) WARN_UNUSED_RESULT
;
343 // Don't respond now, but promise to call Respond(...) later.
344 ResponseAction
RespondLater() WARN_UNUSED_RESULT
;
346 // This is the return value of the EXTENSION_FUNCTION_VALIDATE macro, which
347 // needs to work from Run(), RunAsync(), and RunSync(). The former of those
348 // has a different return type (ResponseAction) than the latter two (bool).
349 static ResponseAction
ValidationFailure(ExtensionFunction
* function
)
352 // If RespondLater() was returned from Run(), functions must at some point
353 // call Respond() with |result| as their result.
355 // More specifically: call this iff Run() has already executed, it returned
356 // RespondLater(), and Respond(...) hasn't already been called.
357 void Respond(ResponseValue result
);
359 virtual ~ExtensionFunction();
361 // Helper method for ExtensionFunctionDeleteTraits. Deletes this object.
362 virtual void Destruct() const = 0;
364 // Do not call this function directly, return the appropriate ResponseAction
365 // from Run() instead. If using RespondLater then call Respond().
367 // Call with true to indicate success, false to indicate failure, in which
368 // case please set |error_|.
369 virtual void SendResponse(bool success
) = 0;
371 // Common implementation for SendResponse.
372 void SendResponseImpl(bool success
);
374 // Return true if the argument to this function at |index| was provided and
376 bool HasOptionalArgument(size_t index
);
378 // Id of this request, used to map the response back to the caller.
381 // The id of the profile of this function's extension.
384 // The extension that called this function.
385 scoped_refptr
<const extensions::Extension
> extension_
;
387 // The name of this function.
390 // The URL of the frame which is making this request
393 // True if the js caller provides a callback function to receive the response
397 // True if this callback should include information from incognito contexts
398 // even if our profile_ is non-incognito. Note that in the case of a "split"
399 // mode extension, this will always be false, and we will limit access to
400 // data from within the same profile_ (either incognito or not).
401 bool include_incognito_
;
403 // True if the call was made in response of user gesture.
406 // The arguments to the API. Only non-null if argument were specified.
407 scoped_ptr
<base::ListValue
> args_
;
409 // The results of the API. This should be populated by the derived class
410 // before SendResponse() is called.
411 scoped_ptr
<base::ListValue
> results_
;
413 // Any detailed error from the API. This should be populated by the derived
414 // class before Run() returns.
417 // Any class that gets a malformed message should set this to true before
418 // returning. Usually we want to kill the message sending process.
421 // The sample value to record with the histogram API when the function
423 extensions::functions::HistogramValue histogram_value_
;
425 // The callback to run once the function has done execution.
426 ResponseCallback response_callback_
;
428 // The ID of the tab triggered this function call, or -1 if there is no tab.
431 // The type of the JavaScript context where this call originated.
432 extensions::Feature::Context source_context_type_
;
434 // The process ID of the page that triggered this function call, or -1
436 int source_process_id_
;
439 void OnRespondingLater(ResponseValue response
);
441 DISALLOW_COPY_AND_ASSIGN(ExtensionFunction
);
444 // Extension functions that run on the UI thread. Most functions fall into
446 class UIThreadExtensionFunction
: public ExtensionFunction
{
448 // TODO(yzshen): We should be able to remove this interface now that we
449 // support overriding the response callback.
450 // A delegate for use in testing, to intercept the call to SendResponse.
451 class DelegateForTests
{
453 virtual void OnSendResponse(UIThreadExtensionFunction
* function
,
455 bool bad_message
) = 0;
458 UIThreadExtensionFunction();
460 UIThreadExtensionFunction
* AsUIThreadExtensionFunction() override
;
462 void set_test_delegate(DelegateForTests
* delegate
) {
463 delegate_
= delegate
;
466 // Called when a message was received.
467 // Should return true if it processed the message.
468 virtual bool OnMessageReceived(const IPC::Message
& message
);
470 // Set the browser context which contains the extension that has originated
471 // this function call.
472 void set_browser_context(content::BrowserContext
* context
) {
475 content::BrowserContext
* browser_context() const { return context_
; }
477 // DEPRECATED: Please use render_frame_host().
478 // TODO(devlin): Remove this once all callers are updated to use
479 // render_frame_host().
480 content::RenderViewHost
* render_view_host_do_not_use() const;
482 void SetRenderFrameHost(content::RenderFrameHost
* render_frame_host
);
483 content::RenderFrameHost
* render_frame_host() const {
484 return render_frame_host_
;
487 void set_dispatcher(const base::WeakPtr
<
488 extensions::ExtensionFunctionDispatcher
>& dispatcher
) {
489 dispatcher_
= dispatcher
;
491 extensions::ExtensionFunctionDispatcher
* dispatcher() const {
492 return dispatcher_
.get();
495 // Gets the "current" web contents if any. If there is no associated web
496 // contents then defaults to the foremost one.
497 // NOTE: "current" can mean different things in different contexts. You
498 // probably want to use GetSenderWebContents().
499 virtual content::WebContents
* GetAssociatedWebContents();
501 // Returns the web contents associated with the sending |render_frame_host_|.
503 content::WebContents
* GetSenderWebContents();
506 // Emits a message to the extension's devtools console.
507 void WriteToConsole(content::ConsoleMessageLevel level
,
508 const std::string
& message
);
510 friend struct content::BrowserThread::DeleteOnThread
<
511 content::BrowserThread::UI
>;
512 friend class base::DeleteHelper
<UIThreadExtensionFunction
>;
514 ~UIThreadExtensionFunction() override
;
516 void SendResponse(bool success
) override
;
518 // Sets the Blob UUIDs whose ownership is being transferred to the renderer.
519 void SetTransferredBlobUUIDs(const std::vector
<std::string
>& blob_uuids
);
521 // The BrowserContext of this function's extension.
522 // TODO(devlin): Grr... protected members. Move this to be private.
523 content::BrowserContext
* context_
;
526 class RenderFrameHostTracker
;
528 void Destruct() const override
;
530 // The dispatcher that will service this extension function call.
531 base::WeakPtr
<extensions::ExtensionFunctionDispatcher
> dispatcher_
;
533 // The RenderFrameHost we will send responses to.
534 content::RenderFrameHost
* render_frame_host_
;
536 scoped_ptr
<RenderFrameHostTracker
> tracker_
;
538 DelegateForTests
* delegate_
;
540 // The blobs transferred to the renderer process.
541 std::vector
<std::string
> transferred_blob_uuids_
;
543 DISALLOW_COPY_AND_ASSIGN(UIThreadExtensionFunction
);
546 // Extension functions that run on the IO thread. This type of function avoids
547 // a roundtrip to and from the UI thread (because communication with the
548 // extension process happens on the IO thread). It's intended to be used when
549 // performance is critical (e.g. the webRequest API which can block network
550 // requests). Generally, UIThreadExtensionFunction is more appropriate and will
551 // be easier to use and interface with the rest of the browser.
552 class IOThreadExtensionFunction
: public ExtensionFunction
{
554 IOThreadExtensionFunction();
556 IOThreadExtensionFunction
* AsIOThreadExtensionFunction() override
;
559 base::WeakPtr
<extensions::IOThreadExtensionMessageFilter
> ipc_sender
,
561 ipc_sender_
= ipc_sender
;
562 routing_id_
= routing_id
;
565 base::WeakPtr
<extensions::IOThreadExtensionMessageFilter
> ipc_sender_weak()
570 int routing_id() const { return routing_id_
; }
572 void set_extension_info_map(const extensions::InfoMap
* extension_info_map
) {
573 extension_info_map_
= extension_info_map
;
575 const extensions::InfoMap
* extension_info_map() const {
576 return extension_info_map_
.get();
580 friend struct content::BrowserThread::DeleteOnThread
<
581 content::BrowserThread::IO
>;
582 friend class base::DeleteHelper
<IOThreadExtensionFunction
>;
584 ~IOThreadExtensionFunction() override
;
586 void Destruct() const override
;
588 void SendResponse(bool success
) override
;
591 base::WeakPtr
<extensions::IOThreadExtensionMessageFilter
> ipc_sender_
;
594 scoped_refptr
<const extensions::InfoMap
> extension_info_map_
;
596 DISALLOW_COPY_AND_ASSIGN(IOThreadExtensionFunction
);
599 // Base class for an extension function that runs asynchronously *relative to
600 // the browser's UI thread*.
601 class AsyncExtensionFunction
: public UIThreadExtensionFunction
{
603 AsyncExtensionFunction();
606 ~AsyncExtensionFunction() override
;
608 // Deprecated: Override UIThreadExtensionFunction and implement Run() instead.
610 // AsyncExtensionFunctions implement this method. Return true to indicate that
611 // nothing has gone wrong yet; SendResponse must be called later. Return false
612 // to respond immediately with an error.
613 virtual bool RunAsync() = 0;
615 // ValidationFailure override to match RunAsync().
616 static bool ValidationFailure(AsyncExtensionFunction
* function
);
619 // If you're hitting a compile error here due to "final" - great! You're
620 // doing the right thing, you just need to extend UIThreadExtensionFunction
621 // instead of AsyncExtensionFunction.
622 ResponseAction
Run() final
;
624 DISALLOW_COPY_AND_ASSIGN(AsyncExtensionFunction
);
627 // A SyncExtensionFunction is an ExtensionFunction that runs synchronously
628 // *relative to the browser's UI thread*. Note that this has nothing to do with
629 // running synchronously relative to the extension process. From the extension
630 // process's point of view, the function is still asynchronous.
632 // This kind of function is convenient for implementing simple APIs that just
633 // need to interact with things on the browser UI thread.
634 class SyncExtensionFunction
: public UIThreadExtensionFunction
{
636 SyncExtensionFunction();
639 ~SyncExtensionFunction() override
;
641 // Deprecated: Override UIThreadExtensionFunction and implement Run() instead.
643 // SyncExtensionFunctions implement this method. Return true to respond
644 // immediately with success, false to respond immediately with an error.
645 virtual bool RunSync() = 0;
647 // ValidationFailure override to match RunSync().
648 static bool ValidationFailure(SyncExtensionFunction
* function
);
651 // If you're hitting a compile error here due to "final" - great! You're
652 // doing the right thing, you just need to extend UIThreadExtensionFunction
653 // instead of SyncExtensionFunction.
654 ResponseAction
Run() final
;
656 DISALLOW_COPY_AND_ASSIGN(SyncExtensionFunction
);
659 class SyncIOThreadExtensionFunction
: public IOThreadExtensionFunction
{
661 SyncIOThreadExtensionFunction();
664 ~SyncIOThreadExtensionFunction() override
;
666 // Deprecated: Override IOThreadExtensionFunction and implement Run() instead.
668 // SyncIOThreadExtensionFunctions implement this method. Return true to
669 // respond immediately with success, false to respond immediately with an
671 virtual bool RunSync() = 0;
673 // ValidationFailure override to match RunSync().
674 static bool ValidationFailure(SyncIOThreadExtensionFunction
* function
);
677 // If you're hitting a compile error here due to "final" - great! You're
678 // doing the right thing, you just need to extend IOThreadExtensionFunction
679 // instead of SyncIOExtensionFunction.
680 ResponseAction
Run() final
;
682 DISALLOW_COPY_AND_ASSIGN(SyncIOThreadExtensionFunction
);
685 #endif // EXTENSIONS_BROWSER_EXTENSION_FUNCTION_H_