Revert 264226 "Reduce dependency of TiclInvalidationService on P..."
[chromium-blink-merge.git] / extensions / browser / extension_function.h
blob60908573eab1616a611548bbf652b700d9896589
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_
8 #include <list>
9 #include <string>
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;
29 namespace base {
30 class ListValue;
31 class Value;
34 namespace content {
35 class BrowserContext;
36 class RenderFrameHost;
37 class RenderViewHost;
38 class WebContents;
41 namespace extensions {
42 class ExtensionFunctionDispatcher;
43 class ExtensionMessageFilter;
44 class QuotaLimitHeuristic;
47 #ifdef NDEBUG
48 #define EXTENSION_FUNCTION_VALIDATE(test) do { \
49 if (!(test)) { \
50 bad_message_ = true; \
51 return false; \
52 } \
53 } while (0)
54 #else // NDEBUG
55 #define EXTENSION_FUNCTION_VALIDATE(test) CHECK(test)
56 #endif // NDEBUG
58 #define EXTENSION_FUNCTION_ERROR(error) do { \
59 error_ = error; \
60 bad_message_ = true; \
61 return false; \
62 } while (0)
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 {
77 public:
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> {
86 public:
87 enum ResponseType {
88 // The function has succeeded.
89 SUCCEEDED,
90 // The function has failed.
91 FAILED,
92 // The input message is malformed.
93 BAD_MESSAGE
96 typedef base::Callback<void(ResponseType type,
97 const base::ListValue& results,
98 const std::string& error)> ResponseCallback;
100 ExtensionFunction();
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
119 // NULL-check.
120 virtual void Run();
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
139 // returns an error.
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_; }
198 protected:
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
207 // success/failure.
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
217 // is non-null.
218 bool HasOptionalArgument(size_t index);
220 // Id of this request, used to map the response back to the caller.
221 int request_id_;
223 // The id of the profile of this function's extension.
224 void* profile_id_;
226 // The extension that called this function.
227 scoped_refptr<const extensions::Extension> extension_;
229 // The name of this function.
230 std::string name_;
232 // The URL of the frame which is making this request
233 GURL source_url_;
235 // True if the js caller provides a callback function to receive the response
236 // of this call.
237 bool has_callback_;
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.
246 bool 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.
257 std::string error_;
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.
261 bool bad_message_;
263 // The sample value to record with the histogram API when the function
264 // is invoked.
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.
271 int source_tab_id_;
273 private:
274 DISALLOW_COPY_AND_ASSIGN(ExtensionFunction);
277 // Extension functions that run on the UI thread. Most functions fall into
278 // this category.
279 class UIThreadExtensionFunction : public ExtensionFunction {
280 public:
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 {
285 public:
286 virtual void OnSendResponse(UIThreadExtensionFunction* function,
287 bool success,
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_browser_context(content::BrowserContext* context) {
306 context_ = context;
308 content::BrowserContext* browser_context() const { return context_; }
310 void SetRenderViewHost(content::RenderViewHost* render_view_host);
311 content::RenderViewHost* render_view_host() const {
312 return render_view_host_;
314 void SetRenderFrameHost(content::RenderFrameHost* render_frame_host);
315 content::RenderFrameHost* render_frame_host() const {
316 return render_frame_host_;
319 void set_dispatcher(const base::WeakPtr<
320 extensions::ExtensionFunctionDispatcher>& dispatcher) {
321 dispatcher_ = dispatcher;
323 extensions::ExtensionFunctionDispatcher* dispatcher() const {
324 return dispatcher_.get();
327 // Gets the "current" web contents if any. If there is no associated web
328 // contents then defaults to the foremost one.
329 virtual content::WebContents* GetAssociatedWebContents();
331 protected:
332 // Emits a message to the extension's devtools console.
333 void WriteToConsole(content::ConsoleMessageLevel level,
334 const std::string& message);
336 friend struct content::BrowserThread::DeleteOnThread<
337 content::BrowserThread::UI>;
338 friend class base::DeleteHelper<UIThreadExtensionFunction>;
340 virtual ~UIThreadExtensionFunction();
342 virtual void SendResponse(bool success) OVERRIDE;
344 // The dispatcher that will service this extension function call.
345 base::WeakPtr<extensions::ExtensionFunctionDispatcher> dispatcher_;
347 // The RenderViewHost we will send responses to.
348 content::RenderViewHost* render_view_host_;
350 // The RenderFrameHost we will send responses to.
351 // NOTE: either render_view_host_ or render_frame_host_ will be set, as we
352 // port code to use RenderFrames for OOPIF. See http://crbug.com/304341.
353 content::RenderFrameHost* render_frame_host_;
355 // The content::BrowserContext of this function's extension.
356 content::BrowserContext* context_;
358 private:
359 class RenderHostTracker;
361 virtual void Destruct() const OVERRIDE;
363 scoped_ptr<RenderHostTracker> tracker_;
365 DelegateForTests* delegate_;
368 // Extension functions that run on the IO thread. This type of function avoids
369 // a roundtrip to and from the UI thread (because communication with the
370 // extension process happens on the IO thread). It's intended to be used when
371 // performance is critical (e.g. the webRequest API which can block network
372 // requests). Generally, UIThreadExtensionFunction is more appropriate and will
373 // be easier to use and interface with the rest of the browser.
374 class IOThreadExtensionFunction : public ExtensionFunction {
375 public:
376 IOThreadExtensionFunction();
378 virtual IOThreadExtensionFunction* AsIOThreadExtensionFunction() OVERRIDE;
380 void set_ipc_sender(
381 base::WeakPtr<extensions::ExtensionMessageFilter> ipc_sender,
382 int routing_id) {
383 ipc_sender_ = ipc_sender;
384 routing_id_ = routing_id;
387 base::WeakPtr<extensions::ExtensionMessageFilter> ipc_sender_weak() const {
388 return ipc_sender_;
391 int routing_id() const { return routing_id_; }
393 void set_extension_info_map(const extensions::InfoMap* extension_info_map) {
394 extension_info_map_ = extension_info_map;
396 const extensions::InfoMap* extension_info_map() const {
397 return extension_info_map_.get();
400 protected:
401 friend struct content::BrowserThread::DeleteOnThread<
402 content::BrowserThread::IO>;
403 friend class base::DeleteHelper<IOThreadExtensionFunction>;
405 virtual ~IOThreadExtensionFunction();
407 virtual void Destruct() const OVERRIDE;
409 virtual void SendResponse(bool success) OVERRIDE;
411 private:
412 base::WeakPtr<extensions::ExtensionMessageFilter> ipc_sender_;
413 int routing_id_;
415 scoped_refptr<const extensions::InfoMap> extension_info_map_;
418 // Base class for an extension function that runs asynchronously *relative to
419 // the browser's UI thread*.
420 class AsyncExtensionFunction : public UIThreadExtensionFunction {
421 public:
422 AsyncExtensionFunction();
424 protected:
425 virtual ~AsyncExtensionFunction();
428 // A SyncExtensionFunction is an ExtensionFunction that runs synchronously
429 // *relative to the browser's UI thread*. Note that this has nothing to do with
430 // running synchronously relative to the extension process. From the extension
431 // process's point of view, the function is still asynchronous.
433 // This kind of function is convenient for implementing simple APIs that just
434 // need to interact with things on the browser UI thread.
435 class SyncExtensionFunction : public UIThreadExtensionFunction {
436 public:
437 SyncExtensionFunction();
439 virtual void Run() OVERRIDE;
441 protected:
442 virtual ~SyncExtensionFunction();
445 class SyncIOThreadExtensionFunction : public IOThreadExtensionFunction {
446 public:
447 SyncIOThreadExtensionFunction();
449 virtual void Run() OVERRIDE;
451 protected:
452 virtual ~SyncIOThreadExtensionFunction();
455 #endif // EXTENSIONS_BROWSER_EXTENSION_FUNCTION_H_