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 "ipc/ipc_message.h"
25 class ExtensionFunction
;
26 class UIThreadExtensionFunction
;
27 class IOThreadExtensionFunction
;
36 class RenderFrameHost
;
41 namespace extensions
{
42 class ExtensionFunctionDispatcher
;
43 class ExtensionMessageFilter
;
44 class QuotaLimitHeuristic
;
52 #define EXTENSION_FUNCTION_VALIDATE(test) \
55 bad_message_ = true; \
56 return ValidationFailure(this); \
60 #define EXTENSION_FUNCTION_VALIDATE(test) CHECK(test)
63 #define EXTENSION_FUNCTION_ERROR(error) \
66 bad_message_ = true; \
67 return ValidationFailure(this); \
70 // Declares a callable extension function with the given |name|. You must also
71 // supply a unique |histogramvalue| used for histograms of extension function
72 // invocation (add new ones at the end of the enum in
73 // extension_function_histogram_value.h).
74 #define DECLARE_EXTENSION_FUNCTION(name, histogramvalue) \
75 public: static const char* function_name() { return name; } \
76 public: static extensions::functions::HistogramValue histogram_value() \
77 { return extensions::functions::histogramvalue; }
79 // Traits that describe how ExtensionFunction should be deleted. This just calls
80 // the virtual "Destruct" method on ExtensionFunction, allowing derived classes
81 // to override the behavior.
82 struct ExtensionFunctionDeleteTraits
{
84 static void Destruct(const ExtensionFunction
* x
);
87 // Abstract base class for extension functions the ExtensionFunctionDispatcher
88 // knows how to dispatch to.
89 class ExtensionFunction
90 : public base::RefCountedThreadSafe
<ExtensionFunction
,
91 ExtensionFunctionDeleteTraits
> {
94 // The function has succeeded.
96 // The function has failed.
98 // The input message is malformed.
102 typedef base::Callback
<void(ResponseType type
,
103 const base::ListValue
& results
,
104 const std::string
& error
)> ResponseCallback
;
108 virtual UIThreadExtensionFunction
* AsUIThreadExtensionFunction();
109 virtual IOThreadExtensionFunction
* AsIOThreadExtensionFunction();
111 // Returns true if the function has permission to run.
113 // The default implementation is to check the Extension's permissions against
114 // what this function requires to run, but some APIs may require finer
115 // grained control, such as tabs.executeScript being allowed for active tabs.
117 // This will be run after the function has been set up but before Run().
118 virtual bool HasPermission();
120 // The result of a function call.
122 // Use NoArguments(), OneArgument(), ArgumentList(), or Error()
123 // rather than this class directly.
124 class ResponseValueObject
{
126 virtual ~ResponseValueObject() {}
128 // Returns true for success, false for failure.
129 virtual bool Apply() = 0;
131 typedef scoped_ptr
<ResponseValueObject
> ResponseValue
;
133 // The action to use when returning from RunAsync.
135 // Use RespondNow() or RespondLater() rather than this class directly.
136 class ResponseActionObject
{
138 virtual ~ResponseActionObject() {}
140 virtual void Execute() = 0;
142 typedef scoped_ptr
<ResponseActionObject
> ResponseAction
;
144 // Runs the function and returns the action to take when the caller is ready
147 // Typical return values might be:
148 // * RespondNow(NoArguments())
149 // * RespondNow(OneArgument(42))
150 // * RespondNow(ArgumentList(my_result.ToValue()))
151 // * RespondNow(Error("Warp core breach"))
152 // * RespondNow(Error("Warp core breach on *", GetURL()))
153 // * RespondLater(), then later,
154 // * Respond(NoArguments())
158 // Callers must call Execute() on the return ResponseAction at some point,
161 // SyncExtensionFunction and AsyncExtensionFunction implement this in terms
162 // of SyncExtensionFunction::RunSync and AsyncExtensionFunction::RunAsync,
163 // but this is deprecated. ExtensionFunction implementations are encouraged
164 // to just implement Run.
165 virtual ResponseAction
Run() WARN_UNUSED_RESULT
= 0;
167 // Gets whether quota should be applied to this individual function
168 // invocation. This is different to GetQuotaLimitHeuristics which is only
169 // invoked once and then cached.
171 // Returns false by default.
172 virtual bool ShouldSkipQuotaLimiting() const;
174 // Optionally adds one or multiple QuotaLimitHeuristic instances suitable for
175 // this function to |heuristics|. The ownership of the new QuotaLimitHeuristic
176 // instances is passed to the owner of |heuristics|.
177 // No quota limiting by default.
179 // Only called once per lifetime of the QuotaService.
180 virtual void GetQuotaLimitHeuristics(
181 extensions::QuotaLimitHeuristics
* heuristics
) const {}
183 // Called when the quota limit has been exceeded. The default implementation
185 virtual void OnQuotaExceeded(const std::string
& violation_error
);
187 // Specifies the raw arguments to the function, as a JSON value.
188 virtual void SetArgs(const base::ListValue
* args
);
190 // Sets a single Value as the results of the function.
191 void SetResult(base::Value
* result
);
193 // Sets multiple Values as the results of the function.
194 void SetResultList(scoped_ptr
<base::ListValue
> results
);
196 // Retrieves the results of the function as a ListValue.
197 const base::ListValue
* GetResultList() const;
199 // Retrieves any error string from the function.
200 virtual std::string
GetError() const;
202 // Sets the function's error string.
203 virtual void SetError(const std::string
& error
);
205 // Sets the function's bad message state.
206 void set_bad_message(bool bad_message
) { bad_message_
= bad_message
; }
208 // Specifies the name of the function.
209 void set_name(const std::string
& name
) { name_
= name
; }
210 const std::string
& name() const { return name_
; }
212 void set_profile_id(void* profile_id
) { profile_id_
= profile_id
; }
213 void* profile_id() const { return profile_id_
; }
215 void set_extension(const extensions::Extension
* extension
) {
216 extension_
= extension
;
218 const extensions::Extension
* GetExtension() const { return extension_
.get(); }
219 const std::string
& extension_id() const { return extension_
->id(); }
221 void set_request_id(int request_id
) { request_id_
= request_id
; }
222 int request_id() { return request_id_
; }
224 void set_source_url(const GURL
& source_url
) { source_url_
= source_url
; }
225 const GURL
& source_url() { return source_url_
; }
227 void set_has_callback(bool has_callback
) { has_callback_
= has_callback
; }
228 bool has_callback() { return has_callback_
; }
230 void set_include_incognito(bool include
) { include_incognito_
= include
; }
231 bool include_incognito() const { return include_incognito_
; }
233 void set_user_gesture(bool user_gesture
) { user_gesture_
= user_gesture
; }
234 bool user_gesture() const { return user_gesture_
; }
236 void set_histogram_value(
237 extensions::functions::HistogramValue histogram_value
) {
238 histogram_value_
= histogram_value
; }
239 extensions::functions::HistogramValue
histogram_value() const {
240 return histogram_value_
; }
242 void set_response_callback(const ResponseCallback
& callback
) {
243 response_callback_
= callback
;
246 void set_source_tab_id(int source_tab_id
) { source_tab_id_
= source_tab_id
; }
247 int source_tab_id() const { return source_tab_id_
; }
250 friend struct ExtensionFunctionDeleteTraits
;
254 // Success, no arguments to pass to caller
255 ResponseValue
NoArguments();
256 // Success, a single argument |arg| to pass to caller. TAKES OWNERSHIP -- a
257 // raw pointer for convenience, since callers usually construct the argument
259 ResponseValue
OneArgument(base::Value
* arg
);
260 // Success, two arguments |arg1| and |arg2| to pass to caller. TAKES
261 // OWNERSHIP -- raw pointers for convenience, since callers usually construct
262 // the argument to this by hand. Note that use of this function may imply you
263 // should be using the generated Result struct and ArgumentList.
264 ResponseValue
TwoArguments(base::Value
* arg1
, base::Value
* arg2
);
265 // Success, a list of arguments |results| to pass to caller. TAKES OWNERSHIP
267 // a scoped_ptr<> for convenience, since callers usually get this from the
268 // result of a ToValue() call on the generated Result struct.
269 ResponseValue
ArgumentList(scoped_ptr
<base::ListValue
> results
);
270 // Error. chrome.runtime.lastError.message will be set to |error|.
271 ResponseValue
Error(const std::string
& error
);
272 // Error with formatting. Args are processed using
273 // ErrorUtils::FormatErrorMessage, that is, each occurence of * is replaced
274 // by the corresponding |s*|:
275 // Error("Error in *: *", "foo", "bar") <--> // Error("Error in foo: bar").
276 ResponseValue
Error(const std::string
& format
, const std::string
& s1
);
277 ResponseValue
Error(const std::string
& format
,
278 const std::string
& s1
,
279 const std::string
& s2
);
280 ResponseValue
Error(const std::string
& format
,
281 const std::string
& s1
,
282 const std::string
& s2
,
283 const std::string
& s3
);
284 // Bad message. A ResponseValue equivalent to EXTENSION_FUNCTION_VALIDATE().
285 ResponseValue
BadMessage();
289 // Respond to the extension immediately with |result|.
290 ResponseAction
RespondNow(ResponseValue result
);
291 // Don't respond now, but promise to call Respond() later.
292 ResponseAction
RespondLater();
294 // This is the return value of the EXTENSION_FUNCTION_VALIDATE macro, which
295 // needs to work from Run(), RunAsync(), and RunSync(). The former of those
296 // has a different return type (ResponseAction) than the latter two (bool).
297 static ResponseAction
ValidationFailure(ExtensionFunction
* function
);
299 // If RespondLater() was used, functions must at some point call Respond()
300 // with |result| as their result.
301 void Respond(ResponseValue result
);
303 virtual ~ExtensionFunction();
305 // Helper method for ExtensionFunctionDeleteTraits. Deletes this object.
306 virtual void Destruct() const = 0;
308 // Do not call this function directly, return the appropriate ResponseAction
309 // from Run() instead. If using RespondLater then call Respond().
311 // Call with true to indicate success, false to indicate failure, in which
312 // case please set |error_|.
313 virtual void SendResponse(bool success
) = 0;
315 // Common implementation for SendResponse.
316 void SendResponseImpl(bool success
);
318 // Return true if the argument to this function at |index| was provided and
320 bool HasOptionalArgument(size_t index
);
322 // Id of this request, used to map the response back to the caller.
325 // The id of the profile of this function's extension.
328 // The extension that called this function.
329 scoped_refptr
<const extensions::Extension
> extension_
;
331 // The name of this function.
334 // The URL of the frame which is making this request
337 // True if the js caller provides a callback function to receive the response
341 // True if this callback should include information from incognito contexts
342 // even if our profile_ is non-incognito. Note that in the case of a "split"
343 // mode extension, this will always be false, and we will limit access to
344 // data from within the same profile_ (either incognito or not).
345 bool include_incognito_
;
347 // True if the call was made in response of user gesture.
350 // The arguments to the API. Only non-null if argument were specified.
351 scoped_ptr
<base::ListValue
> args_
;
353 // The results of the API. This should be populated by the derived class
354 // before SendResponse() is called.
355 scoped_ptr
<base::ListValue
> results_
;
357 // Any detailed error from the API. This should be populated by the derived
358 // class before Run() returns.
361 // Any class that gets a malformed message should set this to true before
362 // returning. Usually we want to kill the message sending process.
365 // The sample value to record with the histogram API when the function
367 extensions::functions::HistogramValue histogram_value_
;
369 // The callback to run once the function has done execution.
370 ResponseCallback response_callback_
;
372 // The ID of the tab triggered this function call, or -1 if there is no tab.
376 void OnRespondingLater(ResponseValue response
);
378 DISALLOW_COPY_AND_ASSIGN(ExtensionFunction
);
381 // Extension functions that run on the UI thread. Most functions fall into
383 class UIThreadExtensionFunction
: public ExtensionFunction
{
385 // TODO(yzshen): We should be able to remove this interface now that we
386 // support overriding the response callback.
387 // A delegate for use in testing, to intercept the call to SendResponse.
388 class DelegateForTests
{
390 virtual void OnSendResponse(UIThreadExtensionFunction
* function
,
392 bool bad_message
) = 0;
395 UIThreadExtensionFunction();
397 virtual UIThreadExtensionFunction
* AsUIThreadExtensionFunction() OVERRIDE
;
399 void set_test_delegate(DelegateForTests
* delegate
) {
400 delegate_
= delegate
;
403 // Called when a message was received.
404 // Should return true if it processed the message.
405 virtual bool OnMessageReceived(const IPC::Message
& message
);
407 // Set the browser context which contains the extension that has originated
408 // this function call.
409 void set_browser_context(content::BrowserContext
* context
) {
412 content::BrowserContext
* browser_context() const { return context_
; }
414 void SetRenderViewHost(content::RenderViewHost
* render_view_host
);
415 content::RenderViewHost
* render_view_host() const {
416 return render_view_host_
;
418 void SetRenderFrameHost(content::RenderFrameHost
* render_frame_host
);
419 content::RenderFrameHost
* render_frame_host() const {
420 return render_frame_host_
;
423 void set_dispatcher(const base::WeakPtr
<
424 extensions::ExtensionFunctionDispatcher
>& dispatcher
) {
425 dispatcher_
= dispatcher
;
427 extensions::ExtensionFunctionDispatcher
* dispatcher() const {
428 return dispatcher_
.get();
431 // Gets the "current" web contents if any. If there is no associated web
432 // contents then defaults to the foremost one.
433 virtual content::WebContents
* GetAssociatedWebContents();
436 // Emits a message to the extension's devtools console.
437 void WriteToConsole(content::ConsoleMessageLevel level
,
438 const std::string
& message
);
440 friend struct content::BrowserThread::DeleteOnThread
<
441 content::BrowserThread::UI
>;
442 friend class base::DeleteHelper
<UIThreadExtensionFunction
>;
444 virtual ~UIThreadExtensionFunction();
446 virtual void SendResponse(bool success
) OVERRIDE
;
448 // Sets the Blob UUIDs whose ownership is being transferred to the renderer.
449 void SetTransferredBlobUUIDs(const std::vector
<std::string
>& blob_uuids
);
451 // The dispatcher that will service this extension function call.
452 base::WeakPtr
<extensions::ExtensionFunctionDispatcher
> dispatcher_
;
454 // The RenderViewHost we will send responses to.
455 content::RenderViewHost
* render_view_host_
;
457 // The RenderFrameHost we will send responses to.
458 // NOTE: either render_view_host_ or render_frame_host_ will be set, as we
459 // port code to use RenderFrames for OOPIF. See http://crbug.com/304341.
460 content::RenderFrameHost
* render_frame_host_
;
462 // The content::BrowserContext of this function's extension.
463 content::BrowserContext
* context_
;
466 class RenderHostTracker
;
468 virtual void Destruct() const OVERRIDE
;
470 // TODO(tommycli): Remove once RenderViewHost is gone.
471 IPC::Sender
* GetIPCSender();
474 scoped_ptr
<RenderHostTracker
> tracker_
;
476 DelegateForTests
* delegate_
;
478 // The blobs transferred to the renderer process.
479 std::vector
<std::string
> transferred_blob_uuids_
;
482 // Extension functions that run on the IO thread. This type of function avoids
483 // a roundtrip to and from the UI thread (because communication with the
484 // extension process happens on the IO thread). It's intended to be used when
485 // performance is critical (e.g. the webRequest API which can block network
486 // requests). Generally, UIThreadExtensionFunction is more appropriate and will
487 // be easier to use and interface with the rest of the browser.
488 class IOThreadExtensionFunction
: public ExtensionFunction
{
490 IOThreadExtensionFunction();
492 virtual IOThreadExtensionFunction
* AsIOThreadExtensionFunction() OVERRIDE
;
495 base::WeakPtr
<extensions::ExtensionMessageFilter
> ipc_sender
,
497 ipc_sender_
= ipc_sender
;
498 routing_id_
= routing_id
;
501 base::WeakPtr
<extensions::ExtensionMessageFilter
> ipc_sender_weak() const {
505 int routing_id() const { return routing_id_
; }
507 void set_extension_info_map(const extensions::InfoMap
* extension_info_map
) {
508 extension_info_map_
= extension_info_map
;
510 const extensions::InfoMap
* extension_info_map() const {
511 return extension_info_map_
.get();
515 friend struct content::BrowserThread::DeleteOnThread
<
516 content::BrowserThread::IO
>;
517 friend class base::DeleteHelper
<IOThreadExtensionFunction
>;
519 virtual ~IOThreadExtensionFunction();
521 virtual void Destruct() const OVERRIDE
;
523 virtual void SendResponse(bool success
) OVERRIDE
;
526 base::WeakPtr
<extensions::ExtensionMessageFilter
> ipc_sender_
;
529 scoped_refptr
<const extensions::InfoMap
> extension_info_map_
;
532 // Base class for an extension function that runs asynchronously *relative to
533 // the browser's UI thread*.
534 class AsyncExtensionFunction
: public UIThreadExtensionFunction
{
536 AsyncExtensionFunction();
539 virtual ~AsyncExtensionFunction();
541 // Deprecated: Override UIThreadExtensionFunction and implement Run() instead.
543 // AsyncExtensionFunctions implement this method. Return true to indicate that
544 // nothing has gone wrong yet; SendResponse must be called later. Return true
545 // to respond immediately with an error.
546 virtual bool RunAsync() = 0;
548 // ValidationFailure override to match RunAsync().
549 static bool ValidationFailure(AsyncExtensionFunction
* function
);
552 virtual ResponseAction
Run() OVERRIDE
;
555 // A SyncExtensionFunction is an ExtensionFunction that runs synchronously
556 // *relative to the browser's UI thread*. Note that this has nothing to do with
557 // running synchronously relative to the extension process. From the extension
558 // process's point of view, the function is still asynchronous.
560 // This kind of function is convenient for implementing simple APIs that just
561 // need to interact with things on the browser UI thread.
562 class SyncExtensionFunction
: public UIThreadExtensionFunction
{
564 SyncExtensionFunction();
567 virtual ~SyncExtensionFunction();
569 // Deprecated: Override UIThreadExtensionFunction and implement Run() instead.
571 // SyncExtensionFunctions implement this method. Return true to respond
572 // immediately with success, false to respond immediately with an error.
573 virtual bool RunSync() = 0;
575 // ValidationFailure override to match RunSync().
576 static bool ValidationFailure(SyncExtensionFunction
* function
);
579 virtual ResponseAction
Run() OVERRIDE
;
582 class SyncIOThreadExtensionFunction
: public IOThreadExtensionFunction
{
584 SyncIOThreadExtensionFunction();
587 virtual ~SyncIOThreadExtensionFunction();
589 // Deprecated: Override IOThreadExtensionFunction and implement Run() instead.
591 // SyncIOThreadExtensionFunctions implement this method. Return true to
592 // respond immediately with success, false to respond immediately with an
594 virtual bool RunSync() = 0;
596 // ValidationFailure override to match RunSync().
597 static bool ValidationFailure(SyncIOThreadExtensionFunction
* function
);
600 virtual ResponseAction
Run() OVERRIDE
;
603 #endif // EXTENSIONS_BROWSER_EXTENSION_FUNCTION_H_