Updating trunk VERSION from 2139.0 to 2140.0
[chromium-blink-merge.git] / extensions / browser / extension_function.h
blob4cb41ad5d30e89eeda6bfce76d168d16e0f10a2c
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 "extensions/common/features/feature.h"
24 #include "ipc/ipc_message.h"
26 class ExtensionFunction;
27 class UIThreadExtensionFunction;
28 class IOThreadExtensionFunction;
30 namespace base {
31 class ListValue;
32 class Value;
35 namespace content {
36 class BrowserContext;
37 class RenderFrameHost;
38 class RenderViewHost;
39 class WebContents;
42 namespace extensions {
43 class ExtensionFunctionDispatcher;
44 class ExtensionMessageFilter;
45 class QuotaLimitHeuristic;
48 namespace IPC {
49 class Sender;
52 #ifdef NDEBUG
53 #define EXTENSION_FUNCTION_VALIDATE(test) \
54 do { \
55 if (!(test)) { \
56 bad_message_ = true; \
57 return ValidationFailure(this); \
58 } \
59 } while (0)
60 #else // NDEBUG
61 #define EXTENSION_FUNCTION_VALIDATE(test) CHECK(test)
62 #endif // NDEBUG
64 #define EXTENSION_FUNCTION_ERROR(error) \
65 do { \
66 error_ = error; \
67 bad_message_ = true; \
68 return ValidationFailure(this); \
69 } while (0)
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 {
84 public:
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> {
93 public:
94 enum ResponseType {
95 // The function has succeeded.
96 SUCCEEDED,
97 // The function has failed.
98 FAILED,
99 // The input message is malformed.
100 BAD_MESSAGE
103 typedef base::Callback<void(ResponseType type,
104 const base::ListValue& results,
105 const std::string& error)> ResponseCallback;
107 ExtensionFunction();
109 virtual UIThreadExtensionFunction* AsUIThreadExtensionFunction();
110 virtual IOThreadExtensionFunction* AsIOThreadExtensionFunction();
112 // Returns true if the function has permission to run.
114 // The default implementation is to check the Extension's permissions against
115 // what this function requires to run, but some APIs may require finer
116 // grained control, such as tabs.executeScript being allowed for active tabs.
118 // This will be run after the function has been set up but before Run().
119 virtual bool HasPermission();
121 // The result of a function call.
123 // Use NoArguments(), OneArgument(), ArgumentList(), or Error()
124 // rather than this class directly.
125 class ResponseValueObject {
126 public:
127 virtual ~ResponseValueObject() {}
129 // Returns true for success, false for failure.
130 virtual bool Apply() = 0;
132 typedef scoped_ptr<ResponseValueObject> ResponseValue;
134 // The action to use when returning from RunAsync.
136 // Use RespondNow() or RespondLater() rather than this class directly.
137 class ResponseActionObject {
138 public:
139 virtual ~ResponseActionObject() {}
141 virtual void Execute() = 0;
143 typedef scoped_ptr<ResponseActionObject> ResponseAction;
145 // Runs the function and returns the action to take when the caller is ready
146 // to respond.
148 // Typical return values might be:
149 // * RespondNow(NoArguments())
150 // * RespondNow(OneArgument(42))
151 // * RespondNow(ArgumentList(my_result.ToValue()))
152 // * RespondNow(Error("Warp core breach"))
153 // * RespondNow(Error("Warp core breach on *", GetURL()))
154 // * RespondLater(), then later,
155 // * Respond(NoArguments())
156 // * ... etc.
159 // Callers must call Execute() on the return ResponseAction at some point,
160 // exactly once.
162 // SyncExtensionFunction and AsyncExtensionFunction implement this in terms
163 // of SyncExtensionFunction::RunSync and AsyncExtensionFunction::RunAsync,
164 // but this is deprecated. ExtensionFunction implementations are encouraged
165 // to just implement Run.
166 virtual ResponseAction Run() WARN_UNUSED_RESULT = 0;
168 // Gets whether quota should be applied to this individual function
169 // invocation. This is different to GetQuotaLimitHeuristics which is only
170 // invoked once and then cached.
172 // Returns false by default.
173 virtual bool ShouldSkipQuotaLimiting() const;
175 // Optionally adds one or multiple QuotaLimitHeuristic instances suitable for
176 // this function to |heuristics|. The ownership of the new QuotaLimitHeuristic
177 // instances is passed to the owner of |heuristics|.
178 // No quota limiting by default.
180 // Only called once per lifetime of the QuotaService.
181 virtual void GetQuotaLimitHeuristics(
182 extensions::QuotaLimitHeuristics* heuristics) const {}
184 // Called when the quota limit has been exceeded. The default implementation
185 // returns an error.
186 virtual void OnQuotaExceeded(const std::string& violation_error);
188 // Specifies the raw arguments to the function, as a JSON value.
189 virtual void SetArgs(const base::ListValue* args);
191 // Sets a single Value as the results of the function.
192 void SetResult(base::Value* result);
194 // Sets multiple Values as the results of the function.
195 void SetResultList(scoped_ptr<base::ListValue> results);
197 // Retrieves the results of the function as a ListValue.
198 const base::ListValue* GetResultList() const;
200 // Retrieves any error string from the function.
201 virtual std::string GetError() const;
203 // Sets the function's error string.
204 virtual void SetError(const std::string& error);
206 // Sets the function's bad message state.
207 void set_bad_message(bool bad_message) { bad_message_ = bad_message; }
209 // Specifies the name of the function.
210 void set_name(const std::string& name) { name_ = name; }
211 const std::string& name() const { return name_; }
213 void set_profile_id(void* profile_id) { profile_id_ = profile_id; }
214 void* profile_id() const { return profile_id_; }
216 void set_extension(const extensions::Extension* extension) {
217 extension_ = extension;
219 const extensions::Extension* extension() const { return extension_.get(); }
220 const std::string& extension_id() const { return extension_->id(); }
222 void set_request_id(int request_id) { request_id_ = request_id; }
223 int request_id() { return request_id_; }
225 void set_source_url(const GURL& source_url) { source_url_ = source_url; }
226 const GURL& source_url() { return source_url_; }
228 void set_has_callback(bool has_callback) { has_callback_ = has_callback; }
229 bool has_callback() { return has_callback_; }
231 void set_include_incognito(bool include) { include_incognito_ = include; }
232 bool include_incognito() const { return include_incognito_; }
234 void set_user_gesture(bool user_gesture) { user_gesture_ = user_gesture; }
235 bool user_gesture() const { return user_gesture_; }
237 void set_histogram_value(
238 extensions::functions::HistogramValue histogram_value) {
239 histogram_value_ = histogram_value; }
240 extensions::functions::HistogramValue histogram_value() const {
241 return histogram_value_; }
243 void set_response_callback(const ResponseCallback& callback) {
244 response_callback_ = callback;
247 void set_source_tab_id(int source_tab_id) { source_tab_id_ = source_tab_id; }
248 int source_tab_id() const { return source_tab_id_; }
250 void set_source_context_type(extensions::Feature::Context type) {
251 source_context_type_ = type;
253 extensions::Feature::Context source_context_type() const {
254 return source_context_type_;
257 protected:
258 friend struct ExtensionFunctionDeleteTraits;
260 // ResponseValues.
262 // Success, no arguments to pass to caller
263 ResponseValue NoArguments();
264 // Success, a single argument |arg| to pass to caller. TAKES OWNERSHIP -- a
265 // raw pointer for convenience, since callers usually construct the argument
266 // to this by hand.
267 ResponseValue OneArgument(base::Value* arg);
268 // Success, two arguments |arg1| and |arg2| to pass to caller. TAKES
269 // OWNERSHIP -- raw pointers for convenience, since callers usually construct
270 // the argument to this by hand. Note that use of this function may imply you
271 // should be using the generated Result struct and ArgumentList.
272 ResponseValue TwoArguments(base::Value* arg1, base::Value* arg2);
273 // Success, a list of arguments |results| to pass to caller. TAKES OWNERSHIP
274 // --
275 // a scoped_ptr<> for convenience, since callers usually get this from the
276 // result of a ToValue() call on the generated Result struct.
277 ResponseValue ArgumentList(scoped_ptr<base::ListValue> results);
278 // Error. chrome.runtime.lastError.message will be set to |error|.
279 ResponseValue Error(const std::string& error);
280 // Error with formatting. Args are processed using
281 // ErrorUtils::FormatErrorMessage, that is, each occurence of * is replaced
282 // by the corresponding |s*|:
283 // Error("Error in *: *", "foo", "bar") <--> // Error("Error in foo: bar").
284 ResponseValue Error(const std::string& format, const std::string& s1);
285 ResponseValue Error(const std::string& format,
286 const std::string& s1,
287 const std::string& s2);
288 ResponseValue Error(const std::string& format,
289 const std::string& s1,
290 const std::string& s2,
291 const std::string& s3);
292 // Bad message. A ResponseValue equivalent to EXTENSION_FUNCTION_VALIDATE().
293 ResponseValue BadMessage();
295 // ResponseActions.
297 // Respond to the extension immediately with |result|.
298 ResponseAction RespondNow(ResponseValue result);
299 // Don't respond now, but promise to call Respond() later.
300 ResponseAction RespondLater();
302 // This is the return value of the EXTENSION_FUNCTION_VALIDATE macro, which
303 // needs to work from Run(), RunAsync(), and RunSync(). The former of those
304 // has a different return type (ResponseAction) than the latter two (bool).
305 static ResponseAction ValidationFailure(ExtensionFunction* function);
307 // If RespondLater() was used, functions must at some point call Respond()
308 // with |result| as their result.
309 void Respond(ResponseValue result);
311 virtual ~ExtensionFunction();
313 // Helper method for ExtensionFunctionDeleteTraits. Deletes this object.
314 virtual void Destruct() const = 0;
316 // Do not call this function directly, return the appropriate ResponseAction
317 // from Run() instead. If using RespondLater then call Respond().
319 // Call with true to indicate success, false to indicate failure, in which
320 // case please set |error_|.
321 virtual void SendResponse(bool success) = 0;
323 // Common implementation for SendResponse.
324 void SendResponseImpl(bool success);
326 // Return true if the argument to this function at |index| was provided and
327 // is non-null.
328 bool HasOptionalArgument(size_t index);
330 // Id of this request, used to map the response back to the caller.
331 int request_id_;
333 // The id of the profile of this function's extension.
334 void* profile_id_;
336 // The extension that called this function.
337 scoped_refptr<const extensions::Extension> extension_;
339 // The name of this function.
340 std::string name_;
342 // The URL of the frame which is making this request
343 GURL source_url_;
345 // True if the js caller provides a callback function to receive the response
346 // of this call.
347 bool has_callback_;
349 // True if this callback should include information from incognito contexts
350 // even if our profile_ is non-incognito. Note that in the case of a "split"
351 // mode extension, this will always be false, and we will limit access to
352 // data from within the same profile_ (either incognito or not).
353 bool include_incognito_;
355 // True if the call was made in response of user gesture.
356 bool user_gesture_;
358 // The arguments to the API. Only non-null if argument were specified.
359 scoped_ptr<base::ListValue> args_;
361 // The results of the API. This should be populated by the derived class
362 // before SendResponse() is called.
363 scoped_ptr<base::ListValue> results_;
365 // Any detailed error from the API. This should be populated by the derived
366 // class before Run() returns.
367 std::string error_;
369 // Any class that gets a malformed message should set this to true before
370 // returning. Usually we want to kill the message sending process.
371 bool bad_message_;
373 // The sample value to record with the histogram API when the function
374 // is invoked.
375 extensions::functions::HistogramValue histogram_value_;
377 // The callback to run once the function has done execution.
378 ResponseCallback response_callback_;
380 // The ID of the tab triggered this function call, or -1 if there is no tab.
381 int source_tab_id_;
383 // The type of the JavaScript context where this call originated.
384 extensions::Feature::Context source_context_type_;
386 private:
387 void OnRespondingLater(ResponseValue response);
389 DISALLOW_COPY_AND_ASSIGN(ExtensionFunction);
392 // Extension functions that run on the UI thread. Most functions fall into
393 // this category.
394 class UIThreadExtensionFunction : public ExtensionFunction {
395 public:
396 // TODO(yzshen): We should be able to remove this interface now that we
397 // support overriding the response callback.
398 // A delegate for use in testing, to intercept the call to SendResponse.
399 class DelegateForTests {
400 public:
401 virtual void OnSendResponse(UIThreadExtensionFunction* function,
402 bool success,
403 bool bad_message) = 0;
406 UIThreadExtensionFunction();
408 virtual UIThreadExtensionFunction* AsUIThreadExtensionFunction() OVERRIDE;
410 void set_test_delegate(DelegateForTests* delegate) {
411 delegate_ = delegate;
414 // Called when a message was received.
415 // Should return true if it processed the message.
416 virtual bool OnMessageReceived(const IPC::Message& message);
418 // Set the browser context which contains the extension that has originated
419 // this function call.
420 void set_browser_context(content::BrowserContext* context) {
421 context_ = context;
423 content::BrowserContext* browser_context() const { return context_; }
425 void SetRenderViewHost(content::RenderViewHost* render_view_host);
426 content::RenderViewHost* render_view_host() const {
427 return render_view_host_;
429 void SetRenderFrameHost(content::RenderFrameHost* render_frame_host);
430 content::RenderFrameHost* render_frame_host() const {
431 return render_frame_host_;
434 void set_dispatcher(const base::WeakPtr<
435 extensions::ExtensionFunctionDispatcher>& dispatcher) {
436 dispatcher_ = dispatcher;
438 extensions::ExtensionFunctionDispatcher* dispatcher() const {
439 return dispatcher_.get();
442 // Gets the "current" web contents if any. If there is no associated web
443 // contents then defaults to the foremost one.
444 virtual content::WebContents* GetAssociatedWebContents();
446 protected:
447 // Emits a message to the extension's devtools console.
448 void WriteToConsole(content::ConsoleMessageLevel level,
449 const std::string& message);
451 friend struct content::BrowserThread::DeleteOnThread<
452 content::BrowserThread::UI>;
453 friend class base::DeleteHelper<UIThreadExtensionFunction>;
455 virtual ~UIThreadExtensionFunction();
457 virtual void SendResponse(bool success) OVERRIDE;
459 // Sets the Blob UUIDs whose ownership is being transferred to the renderer.
460 void SetTransferredBlobUUIDs(const std::vector<std::string>& blob_uuids);
462 // The dispatcher that will service this extension function call.
463 base::WeakPtr<extensions::ExtensionFunctionDispatcher> dispatcher_;
465 // The RenderViewHost we will send responses to.
466 content::RenderViewHost* render_view_host_;
468 // The RenderFrameHost we will send responses to.
469 // NOTE: either render_view_host_ or render_frame_host_ will be set, as we
470 // port code to use RenderFrames for OOPIF. See http://crbug.com/304341.
471 content::RenderFrameHost* render_frame_host_;
473 // The content::BrowserContext of this function's extension.
474 content::BrowserContext* context_;
476 private:
477 class RenderHostTracker;
479 virtual void Destruct() const OVERRIDE;
481 // TODO(tommycli): Remove once RenderViewHost is gone.
482 IPC::Sender* GetIPCSender();
483 int GetRoutingID();
485 scoped_ptr<RenderHostTracker> tracker_;
487 DelegateForTests* delegate_;
489 // The blobs transferred to the renderer process.
490 std::vector<std::string> transferred_blob_uuids_;
493 // Extension functions that run on the IO thread. This type of function avoids
494 // a roundtrip to and from the UI thread (because communication with the
495 // extension process happens on the IO thread). It's intended to be used when
496 // performance is critical (e.g. the webRequest API which can block network
497 // requests). Generally, UIThreadExtensionFunction is more appropriate and will
498 // be easier to use and interface with the rest of the browser.
499 class IOThreadExtensionFunction : public ExtensionFunction {
500 public:
501 IOThreadExtensionFunction();
503 virtual IOThreadExtensionFunction* AsIOThreadExtensionFunction() OVERRIDE;
505 void set_ipc_sender(
506 base::WeakPtr<extensions::ExtensionMessageFilter> ipc_sender,
507 int routing_id) {
508 ipc_sender_ = ipc_sender;
509 routing_id_ = routing_id;
512 base::WeakPtr<extensions::ExtensionMessageFilter> ipc_sender_weak() const {
513 return ipc_sender_;
516 int routing_id() const { return routing_id_; }
518 void set_extension_info_map(const extensions::InfoMap* extension_info_map) {
519 extension_info_map_ = extension_info_map;
521 const extensions::InfoMap* extension_info_map() const {
522 return extension_info_map_.get();
525 protected:
526 friend struct content::BrowserThread::DeleteOnThread<
527 content::BrowserThread::IO>;
528 friend class base::DeleteHelper<IOThreadExtensionFunction>;
530 virtual ~IOThreadExtensionFunction();
532 virtual void Destruct() const OVERRIDE;
534 virtual void SendResponse(bool success) OVERRIDE;
536 private:
537 base::WeakPtr<extensions::ExtensionMessageFilter> ipc_sender_;
538 int routing_id_;
540 scoped_refptr<const extensions::InfoMap> extension_info_map_;
543 // Base class for an extension function that runs asynchronously *relative to
544 // the browser's UI thread*.
545 class AsyncExtensionFunction : public UIThreadExtensionFunction {
546 public:
547 AsyncExtensionFunction();
549 protected:
550 virtual ~AsyncExtensionFunction();
552 // Deprecated: Override UIThreadExtensionFunction and implement Run() instead.
554 // AsyncExtensionFunctions implement this method. Return true to indicate that
555 // nothing has gone wrong yet; SendResponse must be called later. Return true
556 // to respond immediately with an error.
557 virtual bool RunAsync() = 0;
559 // ValidationFailure override to match RunAsync().
560 static bool ValidationFailure(AsyncExtensionFunction* function);
562 private:
563 virtual ResponseAction Run() OVERRIDE;
566 // A SyncExtensionFunction is an ExtensionFunction that runs synchronously
567 // *relative to the browser's UI thread*. Note that this has nothing to do with
568 // running synchronously relative to the extension process. From the extension
569 // process's point of view, the function is still asynchronous.
571 // This kind of function is convenient for implementing simple APIs that just
572 // need to interact with things on the browser UI thread.
573 class SyncExtensionFunction : public UIThreadExtensionFunction {
574 public:
575 SyncExtensionFunction();
577 protected:
578 virtual ~SyncExtensionFunction();
580 // Deprecated: Override UIThreadExtensionFunction and implement Run() instead.
582 // SyncExtensionFunctions implement this method. Return true to respond
583 // immediately with success, false to respond immediately with an error.
584 virtual bool RunSync() = 0;
586 // ValidationFailure override to match RunSync().
587 static bool ValidationFailure(SyncExtensionFunction* function);
589 private:
590 virtual ResponseAction Run() OVERRIDE;
593 class SyncIOThreadExtensionFunction : public IOThreadExtensionFunction {
594 public:
595 SyncIOThreadExtensionFunction();
597 protected:
598 virtual ~SyncIOThreadExtensionFunction();
600 // Deprecated: Override IOThreadExtensionFunction and implement Run() instead.
602 // SyncIOThreadExtensionFunctions implement this method. Return true to
603 // respond immediately with success, false to respond immediately with an
604 // error.
605 virtual bool RunSync() = 0;
607 // ValidationFailure override to match RunSync().
608 static bool ValidationFailure(SyncIOThreadExtensionFunction* function);
610 private:
611 virtual ResponseAction Run() OVERRIDE;
614 #endif // EXTENSIONS_BROWSER_EXTENSION_FUNCTION_H_