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 "chrome/browser/extensions/extension_function_histogram_value.h"
19 #include "content/public/browser/browser_thread.h"
20 #include "content/public/common/console_message_level.h"
21 #include "extensions/browser/info_map.h"
22 #include "extensions/common/extension.h"
23 #include "ipc/ipc_message.h"
25 class ChromeRenderMessageFilter
;
26 class ExtensionFunction
;
27 class ExtensionFunctionDispatcher
;
28 class UIThreadExtensionFunction
;
29 class IOThreadExtensionFunction
;
38 class RenderFrameHost
;
43 namespace extensions
{
44 class QuotaLimitHeuristic
;
48 #define EXTENSION_FUNCTION_VALIDATE(test) do { \
50 bad_message_ = true; \
55 #define EXTENSION_FUNCTION_VALIDATE(test) CHECK(test)
58 #define EXTENSION_FUNCTION_ERROR(error) do { \
60 bad_message_ = true; \
64 // Declares a callable extension function with the given |name|. You must also
65 // supply a unique |histogramvalue| used for histograms of extension function
66 // invocation (add new ones at the end of the enum in
67 // extension_function_histogram_value.h).
68 #define DECLARE_EXTENSION_FUNCTION(name, histogramvalue) \
69 public: static const char* function_name() { return name; } \
70 public: static extensions::functions::HistogramValue histogram_value() \
71 { return extensions::functions::histogramvalue; }
73 // Traits that describe how ExtensionFunction should be deleted. This just calls
74 // the virtual "Destruct" method on ExtensionFunction, allowing derived classes
75 // to override the behavior.
76 struct ExtensionFunctionDeleteTraits
{
78 static void Destruct(const ExtensionFunction
* x
);
81 // Abstract base class for extension functions the ExtensionFunctionDispatcher
82 // knows how to dispatch to.
83 class ExtensionFunction
84 : public base::RefCountedThreadSafe
<ExtensionFunction
,
85 ExtensionFunctionDeleteTraits
> {
88 // The function has succeeded.
90 // The function has failed.
92 // The input message is malformed.
96 typedef base::Callback
<void(ResponseType type
,
97 const base::ListValue
& results
,
98 const std::string
& error
)> ResponseCallback
;
102 virtual UIThreadExtensionFunction
* AsUIThreadExtensionFunction();
103 virtual IOThreadExtensionFunction
* AsIOThreadExtensionFunction();
105 // Returns true if the function has permission to run.
107 // The default implementation is to check the Extension's permissions against
108 // what this function requires to run, but some APIs may require finer
109 // grained control, such as tabs.executeScript being allowed for active tabs.
111 // This will be run after the function has been set up but before Run().
112 virtual bool HasPermission();
114 // Execute the API. Clients should initialize the ExtensionFunction using
115 // SetArgs(), set_request_id(), and the other setters before calling this
116 // method. Derived classes should be ready to return GetResultList() and
117 // GetError() before returning from this function.
118 // Note that once Run() returns, dispatcher() can be NULL, so be sure to
122 // Gets whether quota should be applied to this individual function
123 // invocation. This is different to GetQuotaLimitHeuristics which is only
124 // invoked once and then cached.
126 // Returns false by default.
127 virtual bool ShouldSkipQuotaLimiting() const;
129 // Optionally adds one or multiple QuotaLimitHeuristic instances suitable for
130 // this function to |heuristics|. The ownership of the new QuotaLimitHeuristic
131 // instances is passed to the owner of |heuristics|.
132 // No quota limiting by default.
134 // Only called once per lifetime of the QuotaService.
135 virtual void GetQuotaLimitHeuristics(
136 extensions::QuotaLimitHeuristics
* heuristics
) const {}
138 // Called when the quota limit has been exceeded. The default implementation
140 virtual void OnQuotaExceeded(const std::string
& violation_error
);
142 // Specifies the raw arguments to the function, as a JSON value.
143 virtual void SetArgs(const base::ListValue
* args
);
145 // Sets a single Value as the results of the function.
146 void SetResult(base::Value
* result
);
148 // Retrieves the results of the function as a ListValue.
149 const base::ListValue
* GetResultList();
151 // Retrieves any error string from the function.
152 virtual const std::string
GetError();
154 // Sets the function's error string.
155 virtual void SetError(const std::string
& error
);
157 // Specifies the name of the function.
158 void set_name(const std::string
& name
) { name_
= name
; }
159 const std::string
& name() const { return name_
; }
161 void set_profile_id(void* profile_id
) { profile_id_
= profile_id
; }
162 void* profile_id() const { return profile_id_
; }
164 void set_extension(const extensions::Extension
* extension
) {
165 extension_
= extension
;
167 const extensions::Extension
* GetExtension() const { return extension_
.get(); }
168 const std::string
& extension_id() const { return extension_
->id(); }
170 void set_request_id(int request_id
) { request_id_
= request_id
; }
171 int request_id() { return request_id_
; }
173 void set_source_url(const GURL
& source_url
) { source_url_
= source_url
; }
174 const GURL
& source_url() { return source_url_
; }
176 void set_has_callback(bool has_callback
) { has_callback_
= has_callback
; }
177 bool has_callback() { return has_callback_
; }
179 void set_include_incognito(bool include
) { include_incognito_
= include
; }
180 bool include_incognito() const { return include_incognito_
; }
182 void set_user_gesture(bool user_gesture
) { user_gesture_
= user_gesture
; }
183 bool user_gesture() const { return user_gesture_
; }
185 void set_histogram_value(
186 extensions::functions::HistogramValue histogram_value
) {
187 histogram_value_
= histogram_value
; }
188 extensions::functions::HistogramValue
histogram_value() const {
189 return histogram_value_
; }
191 void set_response_callback(const ResponseCallback
& callback
) {
192 response_callback_
= callback
;
195 void set_source_tab_id(int source_tab_id
) { source_tab_id_
= source_tab_id
; }
196 int source_tab_id() const { return source_tab_id_
; }
199 friend struct ExtensionFunctionDeleteTraits
;
201 virtual ~ExtensionFunction();
203 // Helper method for ExtensionFunctionDeleteTraits. Deletes this object.
204 virtual void Destruct() const = 0;
206 // Derived classes should implement this method to do their work and return
208 virtual bool RunImpl() = 0;
210 // Sends the result back to the extension.
211 virtual void SendResponse(bool success
) = 0;
213 // Common implementation for SendResponse.
214 void SendResponseImpl(bool success
);
216 // Return true if the argument to this function at |index| was provided and
218 bool HasOptionalArgument(size_t index
);
220 // Id of this request, used to map the response back to the caller.
223 // The id of the profile of this function's extension.
226 // The extension that called this function.
227 scoped_refptr
<const extensions::Extension
> extension_
;
229 // The name of this function.
232 // The URL of the frame which is making this request
235 // True if the js caller provides a callback function to receive the response
239 // True if this callback should include information from incognito contexts
240 // even if our profile_ is non-incognito. Note that in the case of a "split"
241 // mode extension, this will always be false, and we will limit access to
242 // data from within the same profile_ (either incognito or not).
243 bool include_incognito_
;
245 // True if the call was made in response of user gesture.
248 // The arguments to the API. Only non-null if argument were specified.
249 scoped_ptr
<base::ListValue
> args_
;
251 // The results of the API. This should be populated by the derived class
252 // before SendResponse() is called.
253 scoped_ptr
<base::ListValue
> results_
;
255 // Any detailed error from the API. This should be populated by the derived
256 // class before Run() returns.
259 // Any class that gets a malformed message should set this to true before
260 // returning. Usually we want to kill the message sending process.
263 // The sample value to record with the histogram API when the function
265 extensions::functions::HistogramValue histogram_value_
;
267 // The callback to run once the function has done execution.
268 ResponseCallback response_callback_
;
270 // The ID of the tab triggered this function call, or -1 if there is no tab.
274 DISALLOW_COPY_AND_ASSIGN(ExtensionFunction
);
277 // Extension functions that run on the UI thread. Most functions fall into
279 class UIThreadExtensionFunction
: public ExtensionFunction
{
281 // TODO(yzshen): We should be able to remove this interface now that we
282 // support overriding the response callback.
283 // A delegate for use in testing, to intercept the call to SendResponse.
284 class DelegateForTests
{
286 virtual void OnSendResponse(UIThreadExtensionFunction
* function
,
288 bool bad_message
) = 0;
291 UIThreadExtensionFunction();
293 virtual UIThreadExtensionFunction
* AsUIThreadExtensionFunction() OVERRIDE
;
295 void set_test_delegate(DelegateForTests
* delegate
) {
296 delegate_
= delegate
;
299 // Called when a message was received.
300 // Should return true if it processed the message.
301 virtual bool OnMessageReceived(const IPC::Message
& message
);
303 // Set the browser context which contains the extension that has originated
304 // this function call.
305 void set_context(content::BrowserContext
* context
) { context_
= context
; }
306 content::BrowserContext
* context() const { return context_
; }
308 void SetRenderViewHost(content::RenderViewHost
* render_view_host
);
309 content::RenderViewHost
* render_view_host() const {
310 return render_view_host_
;
312 void SetRenderFrameHost(content::RenderFrameHost
* render_frame_host
);
313 content::RenderFrameHost
* render_frame_host() const {
314 return render_frame_host_
;
318 const base::WeakPtr
<ExtensionFunctionDispatcher
>& dispatcher
) {
319 dispatcher_
= dispatcher
;
321 ExtensionFunctionDispatcher
* dispatcher() const {
322 return dispatcher_
.get();
325 // Gets the "current" web contents if any. If there is no associated web
326 // contents then defaults to the foremost one.
327 virtual content::WebContents
* GetAssociatedWebContents();
330 // Emits a message to the extension's devtools console.
331 void WriteToConsole(content::ConsoleMessageLevel level
,
332 const std::string
& message
);
334 friend struct content::BrowserThread::DeleteOnThread
<
335 content::BrowserThread::UI
>;
336 friend class base::DeleteHelper
<UIThreadExtensionFunction
>;
338 virtual ~UIThreadExtensionFunction();
340 virtual void SendResponse(bool success
) OVERRIDE
;
342 // The dispatcher that will service this extension function call.
343 base::WeakPtr
<ExtensionFunctionDispatcher
> dispatcher_
;
345 // The RenderViewHost we will send responses to.
346 content::RenderViewHost
* render_view_host_
;
348 // The RenderFrameHost we will send responses to.
349 // NOTE: either render_view_host_ or render_frame_host_ will be set, as we
350 // port code to use RenderFrames for OOPIF. See http://crbug.com/304341.
351 content::RenderFrameHost
* render_frame_host_
;
353 // The content::BrowserContext of this function's extension.
354 content::BrowserContext
* context_
;
357 class RenderHostTracker
;
359 virtual void Destruct() const OVERRIDE
;
361 scoped_ptr
<RenderHostTracker
> tracker_
;
363 DelegateForTests
* delegate_
;
366 // Extension functions that run on the IO thread. This type of function avoids
367 // a roundtrip to and from the UI thread (because communication with the
368 // extension process happens on the IO thread). It's intended to be used when
369 // performance is critical (e.g. the webRequest API which can block network
370 // requests). Generally, UIThreadExtensionFunction is more appropriate and will
371 // be easier to use and interface with the rest of the browser.
372 class IOThreadExtensionFunction
: public ExtensionFunction
{
374 IOThreadExtensionFunction();
376 virtual IOThreadExtensionFunction
* AsIOThreadExtensionFunction() OVERRIDE
;
378 void set_ipc_sender(base::WeakPtr
<ChromeRenderMessageFilter
> ipc_sender
,
380 ipc_sender_
= ipc_sender
;
381 routing_id_
= routing_id
;
384 base::WeakPtr
<ChromeRenderMessageFilter
> ipc_sender_weak() const {
388 int routing_id() const { return routing_id_
; }
390 void set_extension_info_map(const extensions::InfoMap
* extension_info_map
) {
391 extension_info_map_
= extension_info_map
;
393 const extensions::InfoMap
* extension_info_map() const {
394 return extension_info_map_
.get();
398 friend struct content::BrowserThread::DeleteOnThread
<
399 content::BrowserThread::IO
>;
400 friend class base::DeleteHelper
<IOThreadExtensionFunction
>;
402 virtual ~IOThreadExtensionFunction();
404 virtual void Destruct() const OVERRIDE
;
406 virtual void SendResponse(bool success
) OVERRIDE
;
409 base::WeakPtr
<ChromeRenderMessageFilter
> ipc_sender_
;
412 scoped_refptr
<const extensions::InfoMap
> extension_info_map_
;
415 // Base class for an extension function that runs asynchronously *relative to
416 // the browser's UI thread*.
417 class AsyncExtensionFunction
: public UIThreadExtensionFunction
{
419 AsyncExtensionFunction();
422 virtual ~AsyncExtensionFunction();
425 // A SyncExtensionFunction is an ExtensionFunction that runs synchronously
426 // *relative to the browser's UI thread*. Note that this has nothing to do with
427 // running synchronously relative to the extension process. From the extension
428 // process's point of view, the function is still asynchronous.
430 // This kind of function is convenient for implementing simple APIs that just
431 // need to interact with things on the browser UI thread.
432 class SyncExtensionFunction
: public UIThreadExtensionFunction
{
434 SyncExtensionFunction();
436 virtual void Run() OVERRIDE
;
439 virtual ~SyncExtensionFunction();
442 class SyncIOThreadExtensionFunction
: public IOThreadExtensionFunction
{
444 SyncIOThreadExtensionFunction();
446 virtual void Run() OVERRIDE
;
449 virtual ~SyncIOThreadExtensionFunction();
452 #endif // EXTENSIONS_BROWSER_EXTENSION_FUNCTION_H_