Revert of Output closure-compiled JavaScript files (patchset #10 id:180001 of https...
[chromium-blink-merge.git] / extensions / browser / extension_function.h
blobf9a2a79de2d79ec68a07ef2d09412aa6829d1c1c
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 IOThreadExtensionMessageFilter;
45 class QuotaLimitHeuristic;
48 namespace IPC {
49 class Sender;
52 #ifdef NDEBUG
53 #define EXTENSION_FUNCTION_VALIDATE(test) \
54 do { \
55 if (!(test)) { \
56 this->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 this->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 using ResponseCallback = base::Callback<void(
104 ResponseType type,
105 const base::ListValue& results,
106 const std::string& error,
107 extensions::functions::HistogramValue histogram_value)>;
109 ExtensionFunction();
111 virtual UIThreadExtensionFunction* AsUIThreadExtensionFunction();
112 virtual IOThreadExtensionFunction* AsIOThreadExtensionFunction();
114 // Returns true if the function has permission to run.
116 // The default implementation is to check the Extension's permissions against
117 // what this function requires to run, but some APIs may require finer
118 // grained control, such as tabs.executeScript being allowed for active tabs.
120 // This will be run after the function has been set up but before Run().
121 virtual bool HasPermission();
123 // The result of a function call.
125 // Use NoArguments(), OneArgument(), ArgumentList(), or Error()
126 // rather than this class directly.
127 class ResponseValueObject {
128 public:
129 virtual ~ResponseValueObject() {}
131 // Returns true for success, false for failure.
132 virtual bool Apply() = 0;
134 typedef scoped_ptr<ResponseValueObject> ResponseValue;
136 // The action to use when returning from RunAsync.
138 // Use RespondNow() or RespondLater() rather than this class directly.
139 class ResponseActionObject {
140 public:
141 virtual ~ResponseActionObject() {}
143 virtual void Execute() = 0;
145 typedef scoped_ptr<ResponseActionObject> ResponseAction;
147 // Helper class for tests to force all ExtensionFunction::user_gesture()
148 // calls to return true as long as at least one instance of this class
149 // exists.
150 class ScopedUserGestureForTests {
151 public:
152 ScopedUserGestureForTests();
153 ~ScopedUserGestureForTests();
156 // Runs the function and returns the action to take when the caller is ready
157 // to respond.
159 // Typical return values might be:
160 // * RespondNow(NoArguments())
161 // * RespondNow(OneArgument(42))
162 // * RespondNow(ArgumentList(my_result.ToValue()))
163 // * RespondNow(Error("Warp core breach"))
164 // * RespondNow(Error("Warp core breach on *", GetURL()))
165 // * RespondLater(), then later,
166 // * Respond(NoArguments())
167 // * ... etc.
170 // Callers must call Execute() on the return ResponseAction at some point,
171 // exactly once.
173 // SyncExtensionFunction and AsyncExtensionFunction implement this in terms
174 // of SyncExtensionFunction::RunSync and AsyncExtensionFunction::RunAsync,
175 // but this is deprecated. ExtensionFunction implementations are encouraged
176 // to just implement Run.
177 virtual ResponseAction Run() WARN_UNUSED_RESULT = 0;
179 // Gets whether quota should be applied to this individual function
180 // invocation. This is different to GetQuotaLimitHeuristics which is only
181 // invoked once and then cached.
183 // Returns false by default.
184 virtual bool ShouldSkipQuotaLimiting() const;
186 // Optionally adds one or multiple QuotaLimitHeuristic instances suitable for
187 // this function to |heuristics|. The ownership of the new QuotaLimitHeuristic
188 // instances is passed to the owner of |heuristics|.
189 // No quota limiting by default.
191 // Only called once per lifetime of the QuotaService.
192 virtual void GetQuotaLimitHeuristics(
193 extensions::QuotaLimitHeuristics* heuristics) const {}
195 // Called when the quota limit has been exceeded. The default implementation
196 // returns an error.
197 virtual void OnQuotaExceeded(const std::string& violation_error);
199 // Specifies the raw arguments to the function, as a JSON value.
200 virtual void SetArgs(const base::ListValue* args);
202 // Sets a single Value as the results of the function.
203 void SetResult(base::Value* result);
205 // Sets multiple Values as the results of the function.
206 void SetResultList(scoped_ptr<base::ListValue> results);
208 // Retrieves the results of the function as a ListValue.
209 const base::ListValue* GetResultList() const;
211 // Retrieves any error string from the function.
212 virtual std::string GetError() const;
214 // Sets the function's error string.
215 virtual void SetError(const std::string& error);
217 // Sets the function's bad message state.
218 void set_bad_message(bool bad_message) { bad_message_ = bad_message; }
220 // Specifies the name of the function. A long-lived string (such as a string
221 // literal) must be provided.
222 void set_name(const char* name) { name_ = name; }
223 const char* name() const { return name_; }
225 void set_profile_id(void* profile_id) { profile_id_ = profile_id; }
226 void* profile_id() const { return profile_id_; }
228 void set_extension(
229 const scoped_refptr<const extensions::Extension>& extension) {
230 extension_ = extension;
232 const extensions::Extension* extension() const { return extension_.get(); }
233 const std::string& extension_id() const {
234 DCHECK(extension())
235 << "extension_id() called without an Extension. If " << name()
236 << " is allowed to be called without any Extension then you should "
237 << "check extension() first. If not, there is a bug in the Extension "
238 << "platform, so page somebody in extensions/OWNERS";
239 return extension_->id();
242 void set_request_id(int request_id) { request_id_ = request_id; }
243 int request_id() { return request_id_; }
245 void set_source_url(const GURL& source_url) { source_url_ = source_url; }
246 const GURL& source_url() { return source_url_; }
248 void set_has_callback(bool has_callback) { has_callback_ = has_callback; }
249 bool has_callback() { return has_callback_; }
251 void set_include_incognito(bool include) { include_incognito_ = include; }
252 bool include_incognito() const { return include_incognito_; }
254 // Note: consider using ScopedUserGestureForTests instead of calling
255 // set_user_gesture directly.
256 void set_user_gesture(bool user_gesture) { user_gesture_ = user_gesture; }
257 bool user_gesture() const;
259 void set_histogram_value(
260 extensions::functions::HistogramValue histogram_value) {
261 histogram_value_ = histogram_value; }
262 extensions::functions::HistogramValue histogram_value() const {
263 return histogram_value_; }
265 void set_response_callback(const ResponseCallback& callback) {
266 response_callback_ = callback;
269 void set_source_tab_id(int source_tab_id) { source_tab_id_ = source_tab_id; }
270 int source_tab_id() const { return source_tab_id_; }
272 void set_source_context_type(extensions::Feature::Context type) {
273 source_context_type_ = type;
275 extensions::Feature::Context source_context_type() const {
276 return source_context_type_;
279 protected:
280 friend struct ExtensionFunctionDeleteTraits;
282 // ResponseValues.
284 // Success, no arguments to pass to caller.
285 ResponseValue NoArguments();
286 // Success, a single argument |arg| to pass to caller. TAKES OWNERSHIP - a
287 // raw pointer for convenience, since callers usually construct the argument
288 // to this by hand.
289 ResponseValue OneArgument(base::Value* arg);
290 // Success, two arguments |arg1| and |arg2| to pass to caller. TAKES
291 // OWNERSHIP - raw pointers for convenience, since callers usually construct
292 // the argument to this by hand. Note that use of this function may imply you
293 // should be using the generated Result struct and ArgumentList.
294 ResponseValue TwoArguments(base::Value* arg1, base::Value* arg2);
295 // Success, a list of arguments |results| to pass to caller. TAKES OWNERSHIP
296 // - a scoped_ptr<> for convenience, since callers usually get this from the
297 // result of a Create(...) call on the generated Results struct, for example,
298 // alarms::Get::Results::Create(alarm).
299 ResponseValue ArgumentList(scoped_ptr<base::ListValue> results);
300 // Error. chrome.runtime.lastError.message will be set to |error|.
301 ResponseValue Error(const std::string& error);
302 // Error with formatting. Args are processed using
303 // ErrorUtils::FormatErrorMessage, that is, each occurence of * is replaced
304 // by the corresponding |s*|:
305 // Error("Error in *: *", "foo", "bar") <--> Error("Error in foo: bar").
306 ResponseValue Error(const std::string& format, const std::string& s1);
307 ResponseValue Error(const std::string& format,
308 const std::string& s1,
309 const std::string& s2);
310 ResponseValue Error(const std::string& format,
311 const std::string& s1,
312 const std::string& s2,
313 const std::string& s3);
314 // Error with a list of arguments |args| to pass to caller. TAKES OWNERSHIP.
315 // Using this ResponseValue indicates something is wrong with the API.
316 // It shouldn't be possible to have both an error *and* some arguments.
317 // Some legacy APIs do rely on it though, like webstorePrivate.
318 ResponseValue ErrorWithArguments(scoped_ptr<base::ListValue> args,
319 const std::string& error);
320 // Bad message. A ResponseValue equivalent to EXTENSION_FUNCTION_VALIDATE(),
321 // so this will actually kill the renderer and not respond at all.
322 ResponseValue BadMessage();
324 // ResponseActions.
326 // These are exclusively used as return values from Run(). Call Respond(...)
327 // to respond at any other time - but as described below, only after Run()
328 // has already executed, and only if it returned RespondLater().
330 // Respond to the extension immediately with |result|.
331 ResponseAction RespondNow(ResponseValue result) WARN_UNUSED_RESULT;
332 // Don't respond now, but promise to call Respond(...) later.
333 ResponseAction RespondLater() WARN_UNUSED_RESULT;
335 // This is the return value of the EXTENSION_FUNCTION_VALIDATE macro, which
336 // needs to work from Run(), RunAsync(), and RunSync(). The former of those
337 // has a different return type (ResponseAction) than the latter two (bool).
338 static ResponseAction ValidationFailure(ExtensionFunction* function)
339 WARN_UNUSED_RESULT;
341 // If RespondLater() was returned from Run(), functions must at some point
342 // call Respond() with |result| as their result.
344 // More specifically: call this iff Run() has already executed, it returned
345 // RespondLater(), and Respond(...) hasn't already been called.
346 void Respond(ResponseValue result);
348 virtual ~ExtensionFunction();
350 // Helper method for ExtensionFunctionDeleteTraits. Deletes this object.
351 virtual void Destruct() const = 0;
353 // Do not call this function directly, return the appropriate ResponseAction
354 // from Run() instead. If using RespondLater then call Respond().
356 // Call with true to indicate success, false to indicate failure, in which
357 // case please set |error_|.
358 virtual void SendResponse(bool success) = 0;
360 // Common implementation for SendResponse.
361 void SendResponseImpl(bool success);
363 // Return true if the argument to this function at |index| was provided and
364 // is non-null.
365 bool HasOptionalArgument(size_t index);
367 // Id of this request, used to map the response back to the caller.
368 int request_id_;
370 // The id of the profile of this function's extension.
371 void* profile_id_;
373 // The extension that called this function.
374 scoped_refptr<const extensions::Extension> extension_;
376 // The name of this function.
377 const char* name_;
379 // The URL of the frame which is making this request
380 GURL source_url_;
382 // True if the js caller provides a callback function to receive the response
383 // of this call.
384 bool has_callback_;
386 // True if this callback should include information from incognito contexts
387 // even if our profile_ is non-incognito. Note that in the case of a "split"
388 // mode extension, this will always be false, and we will limit access to
389 // data from within the same profile_ (either incognito or not).
390 bool include_incognito_;
392 // True if the call was made in response of user gesture.
393 bool user_gesture_;
395 // The arguments to the API. Only non-null if argument were specified.
396 scoped_ptr<base::ListValue> args_;
398 // The results of the API. This should be populated by the derived class
399 // before SendResponse() is called.
400 scoped_ptr<base::ListValue> results_;
402 // Any detailed error from the API. This should be populated by the derived
403 // class before Run() returns.
404 std::string error_;
406 // Any class that gets a malformed message should set this to true before
407 // returning. Usually we want to kill the message sending process.
408 bool bad_message_;
410 // The sample value to record with the histogram API when the function
411 // is invoked.
412 extensions::functions::HistogramValue histogram_value_;
414 // The callback to run once the function has done execution.
415 ResponseCallback response_callback_;
417 // The ID of the tab triggered this function call, or -1 if there is no tab.
418 int source_tab_id_;
420 // The type of the JavaScript context where this call originated.
421 extensions::Feature::Context source_context_type_;
423 private:
424 void OnRespondingLater(ResponseValue response);
426 DISALLOW_COPY_AND_ASSIGN(ExtensionFunction);
429 // Extension functions that run on the UI thread. Most functions fall into
430 // this category.
431 class UIThreadExtensionFunction : public ExtensionFunction {
432 public:
433 // TODO(yzshen): We should be able to remove this interface now that we
434 // support overriding the response callback.
435 // A delegate for use in testing, to intercept the call to SendResponse.
436 class DelegateForTests {
437 public:
438 virtual void OnSendResponse(UIThreadExtensionFunction* function,
439 bool success,
440 bool bad_message) = 0;
443 UIThreadExtensionFunction();
445 UIThreadExtensionFunction* AsUIThreadExtensionFunction() override;
447 void set_test_delegate(DelegateForTests* delegate) {
448 delegate_ = delegate;
451 // Called when a message was received.
452 // Should return true if it processed the message.
453 virtual bool OnMessageReceived(const IPC::Message& message);
455 // Set the browser context which contains the extension that has originated
456 // this function call.
457 void set_browser_context(content::BrowserContext* context) {
458 context_ = context;
460 content::BrowserContext* browser_context() const { return context_; }
462 void SetRenderViewHost(content::RenderViewHost* render_view_host);
463 content::RenderViewHost* render_view_host() const {
464 return render_view_host_;
466 void SetRenderFrameHost(content::RenderFrameHost* render_frame_host);
467 content::RenderFrameHost* render_frame_host() const {
468 return render_frame_host_;
471 void set_dispatcher(const base::WeakPtr<
472 extensions::ExtensionFunctionDispatcher>& dispatcher) {
473 dispatcher_ = dispatcher;
475 extensions::ExtensionFunctionDispatcher* dispatcher() const {
476 return dispatcher_.get();
479 // Gets the "current" web contents if any. If there is no associated web
480 // contents then defaults to the foremost one.
481 // NOTE: "current" can mean different things in different contexts. You
482 // probably want to use GetSenderWebContents().
483 virtual content::WebContents* GetAssociatedWebContents();
485 // Returns the web contents associated with the sending |render_view_host_|.
486 // This can be null.
487 content::WebContents* GetSenderWebContents();
489 protected:
490 // Emits a message to the extension's devtools console.
491 void WriteToConsole(content::ConsoleMessageLevel level,
492 const std::string& message);
494 friend struct content::BrowserThread::DeleteOnThread<
495 content::BrowserThread::UI>;
496 friend class base::DeleteHelper<UIThreadExtensionFunction>;
498 ~UIThreadExtensionFunction() override;
500 void SendResponse(bool success) override;
502 // Sets the Blob UUIDs whose ownership is being transferred to the renderer.
503 void SetTransferredBlobUUIDs(const std::vector<std::string>& blob_uuids);
505 // The dispatcher that will service this extension function call.
506 base::WeakPtr<extensions::ExtensionFunctionDispatcher> dispatcher_;
508 // The RenderViewHost we will send responses to.
509 content::RenderViewHost* render_view_host_;
511 // The RenderFrameHost we will send responses to.
512 // NOTE: either render_view_host_ or render_frame_host_ will be set, as we
513 // port code to use RenderFrames for OOPIF. See http://crbug.com/304341.
514 content::RenderFrameHost* render_frame_host_;
516 // The content::BrowserContext of this function's extension.
517 content::BrowserContext* context_;
519 private:
520 class RenderHostTracker;
522 void Destruct() const override;
524 // TODO(tommycli): Remove once RenderViewHost is gone.
525 IPC::Sender* GetIPCSender();
526 int GetRoutingID();
528 scoped_ptr<RenderHostTracker> tracker_;
530 DelegateForTests* delegate_;
532 // The blobs transferred to the renderer process.
533 std::vector<std::string> transferred_blob_uuids_;
536 // Extension functions that run on the IO thread. This type of function avoids
537 // a roundtrip to and from the UI thread (because communication with the
538 // extension process happens on the IO thread). It's intended to be used when
539 // performance is critical (e.g. the webRequest API which can block network
540 // requests). Generally, UIThreadExtensionFunction is more appropriate and will
541 // be easier to use and interface with the rest of the browser.
542 class IOThreadExtensionFunction : public ExtensionFunction {
543 public:
544 IOThreadExtensionFunction();
546 IOThreadExtensionFunction* AsIOThreadExtensionFunction() override;
548 void set_ipc_sender(
549 base::WeakPtr<extensions::IOThreadExtensionMessageFilter> ipc_sender,
550 int routing_id) {
551 ipc_sender_ = ipc_sender;
552 routing_id_ = routing_id;
555 base::WeakPtr<extensions::IOThreadExtensionMessageFilter> ipc_sender_weak()
556 const {
557 return ipc_sender_;
560 int routing_id() const { return routing_id_; }
562 void set_extension_info_map(const extensions::InfoMap* extension_info_map) {
563 extension_info_map_ = extension_info_map;
565 const extensions::InfoMap* extension_info_map() const {
566 return extension_info_map_.get();
569 protected:
570 friend struct content::BrowserThread::DeleteOnThread<
571 content::BrowserThread::IO>;
572 friend class base::DeleteHelper<IOThreadExtensionFunction>;
574 ~IOThreadExtensionFunction() override;
576 void Destruct() const override;
578 void SendResponse(bool success) override;
580 private:
581 base::WeakPtr<extensions::IOThreadExtensionMessageFilter> ipc_sender_;
582 int routing_id_;
584 scoped_refptr<const extensions::InfoMap> extension_info_map_;
587 // Base class for an extension function that runs asynchronously *relative to
588 // the browser's UI thread*.
589 class AsyncExtensionFunction : public UIThreadExtensionFunction {
590 public:
591 AsyncExtensionFunction();
593 protected:
594 ~AsyncExtensionFunction() override;
596 // Deprecated: Override UIThreadExtensionFunction and implement Run() instead.
598 // AsyncExtensionFunctions implement this method. Return true to indicate that
599 // nothing has gone wrong yet; SendResponse must be called later. Return false
600 // to respond immediately with an error.
601 virtual bool RunAsync() = 0;
603 // ValidationFailure override to match RunAsync().
604 static bool ValidationFailure(AsyncExtensionFunction* function);
606 private:
607 // If you're hitting a compile error here due to "final" - great! You're
608 // doing the right thing, you just need to extend UIThreadExtensionFunction
609 // instead of AsyncExtensionFunction.
610 ResponseAction Run() final;
613 // A SyncExtensionFunction is an ExtensionFunction that runs synchronously
614 // *relative to the browser's UI thread*. Note that this has nothing to do with
615 // running synchronously relative to the extension process. From the extension
616 // process's point of view, the function is still asynchronous.
618 // This kind of function is convenient for implementing simple APIs that just
619 // need to interact with things on the browser UI thread.
620 class SyncExtensionFunction : public UIThreadExtensionFunction {
621 public:
622 SyncExtensionFunction();
624 protected:
625 ~SyncExtensionFunction() override;
627 // Deprecated: Override UIThreadExtensionFunction and implement Run() instead.
629 // SyncExtensionFunctions implement this method. Return true to respond
630 // immediately with success, false to respond immediately with an error.
631 virtual bool RunSync() = 0;
633 // ValidationFailure override to match RunSync().
634 static bool ValidationFailure(SyncExtensionFunction* function);
636 private:
637 // If you're hitting a compile error here due to "final" - great! You're
638 // doing the right thing, you just need to extend UIThreadExtensionFunction
639 // instead of SyncExtensionFunction.
640 ResponseAction Run() final;
643 class SyncIOThreadExtensionFunction : public IOThreadExtensionFunction {
644 public:
645 SyncIOThreadExtensionFunction();
647 protected:
648 ~SyncIOThreadExtensionFunction() override;
650 // Deprecated: Override IOThreadExtensionFunction and implement Run() instead.
652 // SyncIOThreadExtensionFunctions implement this method. Return true to
653 // respond immediately with success, false to respond immediately with an
654 // error.
655 virtual bool RunSync() = 0;
657 // ValidationFailure override to match RunSync().
658 static bool ValidationFailure(SyncIOThreadExtensionFunction* function);
660 private:
661 // If you're hitting a compile error here due to "final" - great! You're
662 // doing the right thing, you just need to extend IOThreadExtensionFunction
663 // instead of SyncIOExtensionFunction.
664 ResponseAction Run() final;
667 #endif // EXTENSIONS_BROWSER_EXTENSION_FUNCTION_H_