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;
48 #define EXTENSION_FUNCTION_VALIDATE(test) \
51 bad_message_ = true; \
52 return ValidationFailure(this); \
56 #define EXTENSION_FUNCTION_VALIDATE(test) CHECK(test)
59 #define EXTENSION_FUNCTION_ERROR(error) \
62 bad_message_ = true; \
63 return ValidationFailure(this); \
66 // Declares a callable extension function with the given |name|. You must also
67 // supply a unique |histogramvalue| used for histograms of extension function
68 // invocation (add new ones at the end of the enum in
69 // extension_function_histogram_value.h).
70 #define DECLARE_EXTENSION_FUNCTION(name, histogramvalue) \
71 public: static const char* function_name() { return name; } \
72 public: static extensions::functions::HistogramValue histogram_value() \
73 { return extensions::functions::histogramvalue; }
75 // Traits that describe how ExtensionFunction should be deleted. This just calls
76 // the virtual "Destruct" method on ExtensionFunction, allowing derived classes
77 // to override the behavior.
78 struct ExtensionFunctionDeleteTraits {
80 static void Destruct(const ExtensionFunction* x);
83 // Abstract base class for extension functions the ExtensionFunctionDispatcher
84 // knows how to dispatch to.
85 class ExtensionFunction
86 : public base::RefCountedThreadSafe<ExtensionFunction,
87 ExtensionFunctionDeleteTraits> {
90 // The function has succeeded.
92 // The function has failed.
94 // The input message is malformed.
98 typedef base::Callback<void(ResponseType type,
99 const base::ListValue& results,
100 const std::string& error)> ResponseCallback;
104 virtual UIThreadExtensionFunction* AsUIThreadExtensionFunction();
105 virtual IOThreadExtensionFunction* AsIOThreadExtensionFunction();
107 // Returns true if the function has permission to run.
109 // The default implementation is to check the Extension's permissions against
110 // what this function requires to run, but some APIs may require finer
111 // grained control, such as tabs.executeScript being allowed for active tabs.
113 // This will be run after the function has been set up but before Run().
114 virtual bool HasPermission();
116 // The result of a function call.
118 // Use NoArguments(), SingleArgument(), MultipleArguments(), or Error()
119 // rather than this class directly.
120 class ResponseValueObject {
122 virtual ~ResponseValueObject() {}
124 // Returns true for success, false for failure.
125 virtual bool Apply() = 0;
127 typedef scoped_ptr<ResponseValueObject> ResponseValue;
129 // The action to use when returning from RunAsync.
131 // Use RespondNow() or RespondLater() rather than this class directly.
132 class ResponseActionObject {
134 virtual ~ResponseActionObject() {}
136 virtual void Execute() = 0;
138 typedef scoped_ptr<ResponseActionObject> ResponseAction;
140 // Runs the function and returns the action to take when the caller is ready
143 // Callers must call Execute() on the return ResponseAction at some point,
146 // SyncExtensionFunction and AsyncExtensionFunction implement this in terms
147 // of SyncExtensionFunction::RunSync and AsyncExtensionFunction::RunAsync,
148 // but this is deprecated. ExtensionFunction implementations are encouraged
149 // to just implement Run.
150 virtual ResponseAction Run() WARN_UNUSED_RESULT = 0;
152 // Gets whether quota should be applied to this individual function
153 // invocation. This is different to GetQuotaLimitHeuristics which is only
154 // invoked once and then cached.
156 // Returns false by default.
157 virtual bool ShouldSkipQuotaLimiting() const;
159 // Optionally adds one or multiple QuotaLimitHeuristic instances suitable for
160 // this function to |heuristics|. The ownership of the new QuotaLimitHeuristic
161 // instances is passed to the owner of |heuristics|.
162 // No quota limiting by default.
164 // Only called once per lifetime of the QuotaService.
165 virtual void GetQuotaLimitHeuristics(
166 extensions::QuotaLimitHeuristics* heuristics) const {}
168 // Called when the quota limit has been exceeded. The default implementation
170 virtual void OnQuotaExceeded(const std::string& violation_error);
172 // Specifies the raw arguments to the function, as a JSON value.
173 virtual void SetArgs(const base::ListValue* args);
175 // Sets a single Value as the results of the function.
176 void SetResult(base::Value* result);
178 // Sets multiple Values as the results of the function.
179 void SetResultList(scoped_ptr<base::ListValue> results);
181 // Retrieves the results of the function as a ListValue.
182 const base::ListValue* GetResultList() const;
184 // Retrieves any error string from the function.
185 virtual std::string GetError() const;
187 // Sets the function's error string.
188 virtual void SetError(const std::string& error);
190 // Sets the function's bad message state.
191 void set_bad_message(bool bad_message) { bad_message_ = bad_message; }
193 // Specifies the name of the function.
194 void set_name(const std::string& name) { name_ = name; }
195 const std::string& name() const { return name_; }
197 void set_profile_id(void* profile_id) { profile_id_ = profile_id; }
198 void* profile_id() const { return profile_id_; }
200 void set_extension(const extensions::Extension* extension) {
201 extension_ = extension;
203 const extensions::Extension* GetExtension() const { return extension_.get(); }
204 const std::string& extension_id() const { return extension_->id(); }
206 void set_request_id(int request_id) { request_id_ = request_id; }
207 int request_id() { return request_id_; }
209 void set_source_url(const GURL& source_url) { source_url_ = source_url; }
210 const GURL& source_url() { return source_url_; }
212 void set_has_callback(bool has_callback) { has_callback_ = has_callback; }
213 bool has_callback() { return has_callback_; }
215 void set_include_incognito(bool include) { include_incognito_ = include; }
216 bool include_incognito() const { return include_incognito_; }
218 void set_user_gesture(bool user_gesture) { user_gesture_ = user_gesture; }
219 bool user_gesture() const { return user_gesture_; }
221 void set_histogram_value(
222 extensions::functions::HistogramValue histogram_value) {
223 histogram_value_ = histogram_value; }
224 extensions::functions::HistogramValue histogram_value() const {
225 return histogram_value_; }
227 void set_response_callback(const ResponseCallback& callback) {
228 response_callback_ = callback;
231 void set_source_tab_id(int source_tab_id) { source_tab_id_ = source_tab_id; }
232 int source_tab_id() const { return source_tab_id_; }
235 friend struct ExtensionFunctionDeleteTraits;
239 // Success, no arguments to pass to caller
240 ResponseValue NoArguments();
241 // Success, a single argument |result| to pass to caller. TAKES OWNERSHIP.
242 ResponseValue SingleArgument(base::Value* result);
243 // Success, a list of arguments |results| to pass to caller. TAKES OWNERSHIP.
244 ResponseValue MultipleArguments(base::ListValue* results);
245 // Error. chrome.runtime.lastError.message will be set to |error|.
246 ResponseValue Error(const std::string& error);
247 // Bad message. A ResponseValue equivalent to EXTENSION_FUNCTION_VALIDATE().
248 ResponseValue BadMessage();
252 // Respond to the extension immediately with |result|.
253 ResponseAction RespondNow(ResponseValue result);
254 // Don't respond now, but promise to call Respond() later.
255 ResponseAction RespondLater();
257 // This is the return value of the EXTENSION_FUNCTION_VALIDATE macro, which
258 // needs to work from Run(), RunAsync(), and RunSync(). The former of those
259 // has a different return type (ResponseAction) than the latter two (bool).
260 static ResponseAction ValidationFailure(ExtensionFunction* function);
262 // If RespondLater() was used, functions must at some point call Respond()
263 // with |result| as their result.
264 void Respond(ResponseValue result);
266 virtual ~ExtensionFunction();
268 // Helper method for ExtensionFunctionDeleteTraits. Deletes this object.
269 virtual void Destruct() const = 0;
271 // Do not call this function directly, return the appropriate ResponseAction
272 // from Run() instead. If using RespondLater then call Respond().
274 // Call with true to indicate success, false to indicate failure, in which
275 // case please set |error_|.
276 virtual void SendResponse(bool success) = 0;
278 // Common implementation for SendResponse.
279 void SendResponseImpl(bool success);
281 // Return true if the argument to this function at |index| was provided and
283 bool HasOptionalArgument(size_t index);
285 // Id of this request, used to map the response back to the caller.
288 // The id of the profile of this function's extension.
291 // The extension that called this function.
292 scoped_refptr<const extensions::Extension> extension_;
294 // The name of this function.
297 // The URL of the frame which is making this request
300 // True if the js caller provides a callback function to receive the response
304 // True if this callback should include information from incognito contexts
305 // even if our profile_ is non-incognito. Note that in the case of a "split"
306 // mode extension, this will always be false, and we will limit access to
307 // data from within the same profile_ (either incognito or not).
308 bool include_incognito_;
310 // True if the call was made in response of user gesture.
313 // The arguments to the API. Only non-null if argument were specified.
314 scoped_ptr<base::ListValue> args_;
316 // The results of the API. This should be populated by the derived class
317 // before SendResponse() is called.
318 scoped_ptr<base::ListValue> results_;
320 // Any detailed error from the API. This should be populated by the derived
321 // class before Run() returns.
324 // Any class that gets a malformed message should set this to true before
325 // returning. Usually we want to kill the message sending process.
328 // The sample value to record with the histogram API when the function
330 extensions::functions::HistogramValue histogram_value_;
332 // The callback to run once the function has done execution.
333 ResponseCallback response_callback_;
335 // The ID of the tab triggered this function call, or -1 if there is no tab.
339 void OnRespondingLater(ResponseValue response);
341 DISALLOW_COPY_AND_ASSIGN(ExtensionFunction);
344 // Extension functions that run on the UI thread. Most functions fall into
346 class UIThreadExtensionFunction : public ExtensionFunction {
348 // TODO(yzshen): We should be able to remove this interface now that we
349 // support overriding the response callback.
350 // A delegate for use in testing, to intercept the call to SendResponse.
351 class DelegateForTests {
353 virtual void OnSendResponse(UIThreadExtensionFunction* function,
355 bool bad_message) = 0;
358 UIThreadExtensionFunction();
360 virtual UIThreadExtensionFunction* AsUIThreadExtensionFunction() OVERRIDE;
362 void set_test_delegate(DelegateForTests* delegate) {
363 delegate_ = delegate;
366 // Called when a message was received.
367 // Should return true if it processed the message.
368 virtual bool OnMessageReceived(const IPC::Message& message);
370 // Set the browser context which contains the extension that has originated
371 // this function call.
372 void set_browser_context(content::BrowserContext* context) {
375 content::BrowserContext* browser_context() const { return context_; }
377 void SetRenderViewHost(content::RenderViewHost* render_view_host);
378 content::RenderViewHost* render_view_host() const {
379 return render_view_host_;
381 void SetRenderFrameHost(content::RenderFrameHost* render_frame_host);
382 content::RenderFrameHost* render_frame_host() const {
383 return render_frame_host_;
386 void set_dispatcher(const base::WeakPtr<
387 extensions::ExtensionFunctionDispatcher>& dispatcher) {
388 dispatcher_ = dispatcher;
390 extensions::ExtensionFunctionDispatcher* dispatcher() const {
391 return dispatcher_.get();
394 // Gets the "current" web contents if any. If there is no associated web
395 // contents then defaults to the foremost one.
396 virtual content::WebContents* GetAssociatedWebContents();
399 // Emits a message to the extension's devtools console.
400 void WriteToConsole(content::ConsoleMessageLevel level,
401 const std::string& message);
403 friend struct content::BrowserThread::DeleteOnThread<
404 content::BrowserThread::UI>;
405 friend class base::DeleteHelper<UIThreadExtensionFunction>;
407 virtual ~UIThreadExtensionFunction();
409 virtual void SendResponse(bool success) OVERRIDE;
411 // The dispatcher that will service this extension function call.
412 base::WeakPtr<extensions::ExtensionFunctionDispatcher> dispatcher_;
414 // The RenderViewHost we will send responses to.
415 content::RenderViewHost* render_view_host_;
417 // The RenderFrameHost we will send responses to.
418 // NOTE: either render_view_host_ or render_frame_host_ will be set, as we
419 // port code to use RenderFrames for OOPIF. See http://crbug.com/304341.
420 content::RenderFrameHost* render_frame_host_;
422 // The content::BrowserContext of this function's extension.
423 content::BrowserContext* context_;
426 class RenderHostTracker;
428 virtual void Destruct() const OVERRIDE;
430 scoped_ptr<RenderHostTracker> tracker_;
432 DelegateForTests* delegate_;
435 // Extension functions that run on the IO thread. This type of function avoids
436 // a roundtrip to and from the UI thread (because communication with the
437 // extension process happens on the IO thread). It's intended to be used when
438 // performance is critical (e.g. the webRequest API which can block network
439 // requests). Generally, UIThreadExtensionFunction is more appropriate and will
440 // be easier to use and interface with the rest of the browser.
441 class IOThreadExtensionFunction : public ExtensionFunction {
443 IOThreadExtensionFunction();
445 virtual IOThreadExtensionFunction* AsIOThreadExtensionFunction() OVERRIDE;
448 base::WeakPtr<extensions::ExtensionMessageFilter> ipc_sender,
450 ipc_sender_ = ipc_sender;
451 routing_id_ = routing_id;
454 base::WeakPtr<extensions::ExtensionMessageFilter> ipc_sender_weak() const {
458 int routing_id() const { return routing_id_; }
460 void set_extension_info_map(const extensions::InfoMap* extension_info_map) {
461 extension_info_map_ = extension_info_map;
463 const extensions::InfoMap* extension_info_map() const {
464 return extension_info_map_.get();
468 friend struct content::BrowserThread::DeleteOnThread<
469 content::BrowserThread::IO>;
470 friend class base::DeleteHelper<IOThreadExtensionFunction>;
472 virtual ~IOThreadExtensionFunction();
474 virtual void Destruct() const OVERRIDE;
476 virtual void SendResponse(bool success) OVERRIDE;
479 base::WeakPtr<extensions::ExtensionMessageFilter> ipc_sender_;
482 scoped_refptr<const extensions::InfoMap> extension_info_map_;
485 // Base class for an extension function that runs asynchronously *relative to
486 // the browser's UI thread*.
487 class AsyncExtensionFunction : public UIThreadExtensionFunction {
489 AsyncExtensionFunction();
492 virtual ~AsyncExtensionFunction();
494 // Deprecated: Override UIThreadExtensionFunction and implement Run() instead.
496 // AsyncExtensionFunctions implement this method. Return true to indicate that
497 // nothing has gone wrong yet; SendResponse must be called later. Return true
498 // to respond immediately with an error.
499 virtual bool RunAsync() = 0;
501 // ValidationFailure override to match RunAsync().
502 static bool ValidationFailure(AsyncExtensionFunction* function);
505 virtual ResponseAction Run() OVERRIDE;
508 // A SyncExtensionFunction is an ExtensionFunction that runs synchronously
509 // *relative to the browser's UI thread*. Note that this has nothing to do with
510 // running synchronously relative to the extension process. From the extension
511 // process's point of view, the function is still asynchronous.
513 // This kind of function is convenient for implementing simple APIs that just
514 // need to interact with things on the browser UI thread.
515 class SyncExtensionFunction : public UIThreadExtensionFunction {
517 SyncExtensionFunction();
520 virtual ~SyncExtensionFunction();
522 // Deprecated: Override UIThreadExtensionFunction and implement Run() instead.
524 // SyncExtensionFunctions implement this method. Return true to respond
525 // immediately with success, false to respond immediately with an error.
526 virtual bool RunSync() = 0;
528 // ValidationFailure override to match RunSync().
529 static bool ValidationFailure(SyncExtensionFunction* function);
532 virtual ResponseAction Run() OVERRIDE;
535 class SyncIOThreadExtensionFunction : public IOThreadExtensionFunction {
537 SyncIOThreadExtensionFunction();
540 virtual ~SyncIOThreadExtensionFunction();
542 // Deprecated: Override IOThreadExtensionFunction and implement Run() instead.
544 // SyncIOThreadExtensionFunctions implement this method. Return true to
545 // respond immediately with success, false to respond immediately with an
547 virtual bool RunSync() = 0;
549 // ValidationFailure override to match RunSync().
550 static bool ValidationFailure(SyncIOThreadExtensionFunction* function);
553 virtual ResponseAction Run() OVERRIDE;
556 #endif // EXTENSIONS_BROWSER_EXTENSION_FUNCTION_H_