Supervised user import: Listen for profile creation/deletion
[chromium-blink-merge.git] / extensions / browser / extension_function.h
bloba6d814d571237bea8d1193087dbf8d89bac41bf9
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, a single argument |arg| to pass to caller.
291 ResponseValue OneArgument(scoped_ptr<base::Value> arg);
292 // Success, two arguments |arg1| and |arg2| to pass to caller. TAKES
293 // OWNERSHIP - raw pointers for convenience, since callers usually construct
294 // the argument to this by hand. Note that use of this function may imply you
295 // should be using the generated Result struct and ArgumentList.
296 ResponseValue TwoArguments(base::Value* arg1, base::Value* arg2);
297 // Success, a list of arguments |results| to pass to caller. TAKES OWNERSHIP
298 // - a scoped_ptr<> for convenience, since callers usually get this from the
299 // result of a Create(...) call on the generated Results struct, for example,
300 // alarms::Get::Results::Create(alarm).
301 ResponseValue ArgumentList(scoped_ptr<base::ListValue> results);
302 // Error. chrome.runtime.lastError.message will be set to |error|.
303 ResponseValue Error(const std::string& error);
304 // Error with formatting. Args are processed using
305 // ErrorUtils::FormatErrorMessage, that is, each occurence of * is replaced
306 // by the corresponding |s*|:
307 // Error("Error in *: *", "foo", "bar") <--> Error("Error in foo: bar").
308 ResponseValue Error(const std::string& format, const std::string& s1);
309 ResponseValue Error(const std::string& format,
310 const std::string& s1,
311 const std::string& s2);
312 ResponseValue Error(const std::string& format,
313 const std::string& s1,
314 const std::string& s2,
315 const std::string& s3);
316 // Error with a list of arguments |args| to pass to caller. TAKES OWNERSHIP.
317 // Using this ResponseValue indicates something is wrong with the API.
318 // It shouldn't be possible to have both an error *and* some arguments.
319 // Some legacy APIs do rely on it though, like webstorePrivate.
320 ResponseValue ErrorWithArguments(scoped_ptr<base::ListValue> args,
321 const std::string& error);
322 // Bad message. A ResponseValue equivalent to EXTENSION_FUNCTION_VALIDATE(),
323 // so this will actually kill the renderer and not respond at all.
324 ResponseValue BadMessage();
326 // ResponseActions.
328 // These are exclusively used as return values from Run(). Call Respond(...)
329 // to respond at any other time - but as described below, only after Run()
330 // has already executed, and only if it returned RespondLater().
332 // Respond to the extension immediately with |result|.
333 ResponseAction RespondNow(ResponseValue result) WARN_UNUSED_RESULT;
334 // Don't respond now, but promise to call Respond(...) later.
335 ResponseAction RespondLater() WARN_UNUSED_RESULT;
337 // This is the return value of the EXTENSION_FUNCTION_VALIDATE macro, which
338 // needs to work from Run(), RunAsync(), and RunSync(). The former of those
339 // has a different return type (ResponseAction) than the latter two (bool).
340 static ResponseAction ValidationFailure(ExtensionFunction* function)
341 WARN_UNUSED_RESULT;
343 // If RespondLater() was returned from Run(), functions must at some point
344 // call Respond() with |result| as their result.
346 // More specifically: call this iff Run() has already executed, it returned
347 // RespondLater(), and Respond(...) hasn't already been called.
348 void Respond(ResponseValue result);
350 virtual ~ExtensionFunction();
352 // Helper method for ExtensionFunctionDeleteTraits. Deletes this object.
353 virtual void Destruct() const = 0;
355 // Do not call this function directly, return the appropriate ResponseAction
356 // from Run() instead. If using RespondLater then call Respond().
358 // Call with true to indicate success, false to indicate failure, in which
359 // case please set |error_|.
360 virtual void SendResponse(bool success) = 0;
362 // Common implementation for SendResponse.
363 void SendResponseImpl(bool success);
365 // Return true if the argument to this function at |index| was provided and
366 // is non-null.
367 bool HasOptionalArgument(size_t index);
369 // Id of this request, used to map the response back to the caller.
370 int request_id_;
372 // The id of the profile of this function's extension.
373 void* profile_id_;
375 // The extension that called this function.
376 scoped_refptr<const extensions::Extension> extension_;
378 // The name of this function.
379 const char* name_;
381 // The URL of the frame which is making this request
382 GURL source_url_;
384 // True if the js caller provides a callback function to receive the response
385 // of this call.
386 bool has_callback_;
388 // True if this callback should include information from incognito contexts
389 // even if our profile_ is non-incognito. Note that in the case of a "split"
390 // mode extension, this will always be false, and we will limit access to
391 // data from within the same profile_ (either incognito or not).
392 bool include_incognito_;
394 // True if the call was made in response of user gesture.
395 bool user_gesture_;
397 // The arguments to the API. Only non-null if argument were specified.
398 scoped_ptr<base::ListValue> args_;
400 // The results of the API. This should be populated by the derived class
401 // before SendResponse() is called.
402 scoped_ptr<base::ListValue> results_;
404 // Any detailed error from the API. This should be populated by the derived
405 // class before Run() returns.
406 std::string error_;
408 // Any class that gets a malformed message should set this to true before
409 // returning. Usually we want to kill the message sending process.
410 bool bad_message_;
412 // The sample value to record with the histogram API when the function
413 // is invoked.
414 extensions::functions::HistogramValue histogram_value_;
416 // The callback to run once the function has done execution.
417 ResponseCallback response_callback_;
419 // The ID of the tab triggered this function call, or -1 if there is no tab.
420 int source_tab_id_;
422 // The type of the JavaScript context where this call originated.
423 extensions::Feature::Context source_context_type_;
425 private:
426 void OnRespondingLater(ResponseValue response);
428 DISALLOW_COPY_AND_ASSIGN(ExtensionFunction);
431 // Extension functions that run on the UI thread. Most functions fall into
432 // this category.
433 class UIThreadExtensionFunction : public ExtensionFunction {
434 public:
435 // TODO(yzshen): We should be able to remove this interface now that we
436 // support overriding the response callback.
437 // A delegate for use in testing, to intercept the call to SendResponse.
438 class DelegateForTests {
439 public:
440 virtual void OnSendResponse(UIThreadExtensionFunction* function,
441 bool success,
442 bool bad_message) = 0;
445 UIThreadExtensionFunction();
447 UIThreadExtensionFunction* AsUIThreadExtensionFunction() override;
449 void set_test_delegate(DelegateForTests* delegate) {
450 delegate_ = delegate;
453 // Called when a message was received.
454 // Should return true if it processed the message.
455 virtual bool OnMessageReceived(const IPC::Message& message);
457 // Set the browser context which contains the extension that has originated
458 // this function call.
459 void set_browser_context(content::BrowserContext* context) {
460 context_ = context;
462 content::BrowserContext* browser_context() const { return context_; }
464 void SetRenderViewHost(content::RenderViewHost* render_view_host);
465 content::RenderViewHost* render_view_host() const {
466 return render_view_host_;
468 void SetRenderFrameHost(content::RenderFrameHost* render_frame_host);
469 content::RenderFrameHost* render_frame_host() const {
470 return render_frame_host_;
473 void set_dispatcher(const base::WeakPtr<
474 extensions::ExtensionFunctionDispatcher>& dispatcher) {
475 dispatcher_ = dispatcher;
477 extensions::ExtensionFunctionDispatcher* dispatcher() const {
478 return dispatcher_.get();
481 // Gets the "current" web contents if any. If there is no associated web
482 // contents then defaults to the foremost one.
483 // NOTE: "current" can mean different things in different contexts. You
484 // probably want to use GetSenderWebContents().
485 virtual content::WebContents* GetAssociatedWebContents();
487 // Returns the web contents associated with the sending |render_view_host_|.
488 // This can be null.
489 content::WebContents* GetSenderWebContents();
491 protected:
492 // Emits a message to the extension's devtools console.
493 void WriteToConsole(content::ConsoleMessageLevel level,
494 const std::string& message);
496 friend struct content::BrowserThread::DeleteOnThread<
497 content::BrowserThread::UI>;
498 friend class base::DeleteHelper<UIThreadExtensionFunction>;
500 ~UIThreadExtensionFunction() override;
502 void SendResponse(bool success) override;
504 // Sets the Blob UUIDs whose ownership is being transferred to the renderer.
505 void SetTransferredBlobUUIDs(const std::vector<std::string>& blob_uuids);
507 // The dispatcher that will service this extension function call.
508 base::WeakPtr<extensions::ExtensionFunctionDispatcher> dispatcher_;
510 // The RenderViewHost we will send responses to.
511 content::RenderViewHost* render_view_host_;
513 // The RenderFrameHost we will send responses to.
514 // NOTE: either render_view_host_ or render_frame_host_ will be set, as we
515 // port code to use RenderFrames for OOPIF. See http://crbug.com/304341.
516 content::RenderFrameHost* render_frame_host_;
518 // The content::BrowserContext of this function's extension.
519 content::BrowserContext* context_;
521 private:
522 class RenderHostTracker;
524 void Destruct() const override;
526 // TODO(tommycli): Remove once RenderViewHost is gone.
527 IPC::Sender* GetIPCSender();
528 int GetRoutingID();
530 scoped_ptr<RenderHostTracker> tracker_;
532 DelegateForTests* delegate_;
534 // The blobs transferred to the renderer process.
535 std::vector<std::string> transferred_blob_uuids_;
538 // Extension functions that run on the IO thread. This type of function avoids
539 // a roundtrip to and from the UI thread (because communication with the
540 // extension process happens on the IO thread). It's intended to be used when
541 // performance is critical (e.g. the webRequest API which can block network
542 // requests). Generally, UIThreadExtensionFunction is more appropriate and will
543 // be easier to use and interface with the rest of the browser.
544 class IOThreadExtensionFunction : public ExtensionFunction {
545 public:
546 IOThreadExtensionFunction();
548 IOThreadExtensionFunction* AsIOThreadExtensionFunction() override;
550 void set_ipc_sender(
551 base::WeakPtr<extensions::IOThreadExtensionMessageFilter> ipc_sender,
552 int routing_id) {
553 ipc_sender_ = ipc_sender;
554 routing_id_ = routing_id;
557 base::WeakPtr<extensions::IOThreadExtensionMessageFilter> ipc_sender_weak()
558 const {
559 return ipc_sender_;
562 int routing_id() const { return routing_id_; }
564 void set_extension_info_map(const extensions::InfoMap* extension_info_map) {
565 extension_info_map_ = extension_info_map;
567 const extensions::InfoMap* extension_info_map() const {
568 return extension_info_map_.get();
571 protected:
572 friend struct content::BrowserThread::DeleteOnThread<
573 content::BrowserThread::IO>;
574 friend class base::DeleteHelper<IOThreadExtensionFunction>;
576 ~IOThreadExtensionFunction() override;
578 void Destruct() const override;
580 void SendResponse(bool success) override;
582 private:
583 base::WeakPtr<extensions::IOThreadExtensionMessageFilter> ipc_sender_;
584 int routing_id_;
586 scoped_refptr<const extensions::InfoMap> extension_info_map_;
589 // Base class for an extension function that runs asynchronously *relative to
590 // the browser's UI thread*.
591 class AsyncExtensionFunction : public UIThreadExtensionFunction {
592 public:
593 AsyncExtensionFunction();
595 protected:
596 ~AsyncExtensionFunction() override;
598 // Deprecated: Override UIThreadExtensionFunction and implement Run() instead.
600 // AsyncExtensionFunctions implement this method. Return true to indicate that
601 // nothing has gone wrong yet; SendResponse must be called later. Return false
602 // to respond immediately with an error.
603 virtual bool RunAsync() = 0;
605 // ValidationFailure override to match RunAsync().
606 static bool ValidationFailure(AsyncExtensionFunction* function);
608 private:
609 // If you're hitting a compile error here due to "final" - great! You're
610 // doing the right thing, you just need to extend UIThreadExtensionFunction
611 // instead of AsyncExtensionFunction.
612 ResponseAction Run() final;
615 // A SyncExtensionFunction is an ExtensionFunction that runs synchronously
616 // *relative to the browser's UI thread*. Note that this has nothing to do with
617 // running synchronously relative to the extension process. From the extension
618 // process's point of view, the function is still asynchronous.
620 // This kind of function is convenient for implementing simple APIs that just
621 // need to interact with things on the browser UI thread.
622 class SyncExtensionFunction : public UIThreadExtensionFunction {
623 public:
624 SyncExtensionFunction();
626 protected:
627 ~SyncExtensionFunction() override;
629 // Deprecated: Override UIThreadExtensionFunction and implement Run() instead.
631 // SyncExtensionFunctions implement this method. Return true to respond
632 // immediately with success, false to respond immediately with an error.
633 virtual bool RunSync() = 0;
635 // ValidationFailure override to match RunSync().
636 static bool ValidationFailure(SyncExtensionFunction* function);
638 private:
639 // If you're hitting a compile error here due to "final" - great! You're
640 // doing the right thing, you just need to extend UIThreadExtensionFunction
641 // instead of SyncExtensionFunction.
642 ResponseAction Run() final;
645 class SyncIOThreadExtensionFunction : public IOThreadExtensionFunction {
646 public:
647 SyncIOThreadExtensionFunction();
649 protected:
650 ~SyncIOThreadExtensionFunction() override;
652 // Deprecated: Override IOThreadExtensionFunction and implement Run() instead.
654 // SyncIOThreadExtensionFunctions implement this method. Return true to
655 // respond immediately with success, false to respond immediately with an
656 // error.
657 virtual bool RunSync() = 0;
659 // ValidationFailure override to match RunSync().
660 static bool ValidationFailure(SyncIOThreadExtensionFunction* function);
662 private:
663 // If you're hitting a compile error here due to "final" - great! You're
664 // doing the right thing, you just need to extend IOThreadExtensionFunction
665 // instead of SyncIOExtensionFunction.
666 ResponseAction Run() final;
669 #endif // EXTENSIONS_BROWSER_EXTENSION_FUNCTION_H_