[Smart Lock] Record a detailed UMA metric for each unlock attempt by Smart Lock users.
[chromium-blink-merge.git] / extensions / browser / extension_function.h
blob2e367d33be8597b8c88442b1ea5aedbc966f1806
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 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 // Helper class for tests to force all ExtensionFunction::user_gesture()
146 // calls to return true as long as at least one instance of this class
147 // exists.
148 class ScopedUserGestureForTests {
149 public:
150 ScopedUserGestureForTests();
151 ~ScopedUserGestureForTests();
154 // Runs the function and returns the action to take when the caller is ready
155 // to respond.
157 // Typical return values might be:
158 // * RespondNow(NoArguments())
159 // * RespondNow(OneArgument(42))
160 // * RespondNow(ArgumentList(my_result.ToValue()))
161 // * RespondNow(Error("Warp core breach"))
162 // * RespondNow(Error("Warp core breach on *", GetURL()))
163 // * RespondLater(), then later,
164 // * Respond(NoArguments())
165 // * ... etc.
168 // Callers must call Execute() on the return ResponseAction at some point,
169 // exactly once.
171 // SyncExtensionFunction and AsyncExtensionFunction implement this in terms
172 // of SyncExtensionFunction::RunSync and AsyncExtensionFunction::RunAsync,
173 // but this is deprecated. ExtensionFunction implementations are encouraged
174 // to just implement Run.
175 virtual ResponseAction Run() WARN_UNUSED_RESULT = 0;
177 // Gets whether quota should be applied to this individual function
178 // invocation. This is different to GetQuotaLimitHeuristics which is only
179 // invoked once and then cached.
181 // Returns false by default.
182 virtual bool ShouldSkipQuotaLimiting() const;
184 // Optionally adds one or multiple QuotaLimitHeuristic instances suitable for
185 // this function to |heuristics|. The ownership of the new QuotaLimitHeuristic
186 // instances is passed to the owner of |heuristics|.
187 // No quota limiting by default.
189 // Only called once per lifetime of the QuotaService.
190 virtual void GetQuotaLimitHeuristics(
191 extensions::QuotaLimitHeuristics* heuristics) const {}
193 // Called when the quota limit has been exceeded. The default implementation
194 // returns an error.
195 virtual void OnQuotaExceeded(const std::string& violation_error);
197 // Specifies the raw arguments to the function, as a JSON value.
198 virtual void SetArgs(const base::ListValue* args);
200 // Sets a single Value as the results of the function.
201 void SetResult(base::Value* result);
203 // Sets multiple Values as the results of the function.
204 void SetResultList(scoped_ptr<base::ListValue> results);
206 // Retrieves the results of the function as a ListValue.
207 const base::ListValue* GetResultList() const;
209 // Retrieves any error string from the function.
210 virtual std::string GetError() const;
212 // Sets the function's error string.
213 virtual void SetError(const std::string& error);
215 // Sets the function's bad message state.
216 void set_bad_message(bool bad_message) { bad_message_ = bad_message; }
218 // Specifies the name of the function. A long-lived string (such as a string
219 // literal) must be provided.
220 void set_name(const char* name) { name_ = name; }
221 const char* name() const { return name_; }
223 void set_profile_id(void* profile_id) { profile_id_ = profile_id; }
224 void* profile_id() const { return profile_id_; }
226 void set_extension(
227 const scoped_refptr<const extensions::Extension>& extension) {
228 extension_ = extension;
230 const extensions::Extension* extension() const { return extension_.get(); }
231 const std::string& extension_id() const {
232 DCHECK(extension())
233 << "extension_id() called without an Extension. If " << name()
234 << " is allowed to be called without any Extension then you should "
235 << "check extension() first. If not, there is a bug in the Extension "
236 << "platform, so page somebody in extensions/OWNERS";
237 return extension_->id();
240 void set_request_id(int request_id) { request_id_ = request_id; }
241 int request_id() { return request_id_; }
243 void set_source_url(const GURL& source_url) { source_url_ = source_url; }
244 const GURL& source_url() { return source_url_; }
246 void set_has_callback(bool has_callback) { has_callback_ = has_callback; }
247 bool has_callback() { return has_callback_; }
249 void set_include_incognito(bool include) { include_incognito_ = include; }
250 bool include_incognito() const { return include_incognito_; }
252 // Note: consider using ScopedUserGestureForTests instead of calling
253 // set_user_gesture directly.
254 void set_user_gesture(bool user_gesture) { user_gesture_ = user_gesture; }
255 bool user_gesture() const;
257 void set_histogram_value(
258 extensions::functions::HistogramValue histogram_value) {
259 histogram_value_ = histogram_value; }
260 extensions::functions::HistogramValue histogram_value() const {
261 return histogram_value_; }
263 void set_response_callback(const ResponseCallback& callback) {
264 response_callback_ = callback;
267 void set_source_tab_id(int source_tab_id) { source_tab_id_ = source_tab_id; }
268 int source_tab_id() const { return source_tab_id_; }
270 void set_source_context_type(extensions::Feature::Context type) {
271 source_context_type_ = type;
273 extensions::Feature::Context source_context_type() const {
274 return source_context_type_;
277 protected:
278 friend struct ExtensionFunctionDeleteTraits;
280 // ResponseValues.
282 // Success, no arguments to pass to caller.
283 ResponseValue NoArguments();
284 // Success, a single argument |arg| to pass to caller. TAKES OWNERSHIP - a
285 // raw pointer for convenience, since callers usually construct the argument
286 // to this by hand.
287 ResponseValue OneArgument(base::Value* arg);
288 // Success, two arguments |arg1| and |arg2| to pass to caller. TAKES
289 // OWNERSHIP - raw pointers for convenience, since callers usually construct
290 // the argument to this by hand. Note that use of this function may imply you
291 // should be using the generated Result struct and ArgumentList.
292 ResponseValue TwoArguments(base::Value* arg1, base::Value* arg2);
293 // Success, a list of arguments |results| to pass to caller. TAKES OWNERSHIP
294 // - a scoped_ptr<> for convenience, since callers usually get this from the
295 // result of a Create(...) call on the generated Results struct, for example,
296 // alarms::Get::Results::Create(alarm).
297 ResponseValue ArgumentList(scoped_ptr<base::ListValue> results);
298 // Error. chrome.runtime.lastError.message will be set to |error|.
299 ResponseValue Error(const std::string& error);
300 // Error with formatting. Args are processed using
301 // ErrorUtils::FormatErrorMessage, that is, each occurence of * is replaced
302 // by the corresponding |s*|:
303 // Error("Error in *: *", "foo", "bar") <--> Error("Error in foo: bar").
304 ResponseValue Error(const std::string& format, const std::string& s1);
305 ResponseValue Error(const std::string& format,
306 const std::string& s1,
307 const std::string& s2);
308 ResponseValue Error(const std::string& format,
309 const std::string& s1,
310 const std::string& s2,
311 const std::string& s3);
312 // Error with a list of arguments |args| to pass to caller. TAKES OWNERSHIP.
313 // Using this ResponseValue indicates something is wrong with the API.
314 // It shouldn't be possible to have both an error *and* some arguments.
315 // Some legacy APIs do rely on it though, like webstorePrivate.
316 ResponseValue ErrorWithArguments(scoped_ptr<base::ListValue> args,
317 const std::string& error);
318 // Bad message. A ResponseValue equivalent to EXTENSION_FUNCTION_VALIDATE(),
319 // so this will actually kill the renderer and not respond at all.
320 ResponseValue BadMessage();
322 // ResponseActions.
324 // Respond to the extension immediately with |result|.
325 ResponseAction RespondNow(ResponseValue result);
326 // Don't respond now, but promise to call Respond(...) later.
327 ResponseAction RespondLater();
329 // This is the return value of the EXTENSION_FUNCTION_VALIDATE macro, which
330 // needs to work from Run(), RunAsync(), and RunSync(). The former of those
331 // has a different return type (ResponseAction) than the latter two (bool).
332 static ResponseAction ValidationFailure(ExtensionFunction* function);
334 // If RespondLater() was used, functions must at some point call Respond()
335 // with |result| as their result.
336 void Respond(ResponseValue result);
338 virtual ~ExtensionFunction();
340 // Helper method for ExtensionFunctionDeleteTraits. Deletes this object.
341 virtual void Destruct() const = 0;
343 // Do not call this function directly, return the appropriate ResponseAction
344 // from Run() instead. If using RespondLater then call Respond().
346 // Call with true to indicate success, false to indicate failure, in which
347 // case please set |error_|.
348 virtual void SendResponse(bool success) = 0;
350 // Common implementation for SendResponse.
351 void SendResponseImpl(bool success);
353 // Return true if the argument to this function at |index| was provided and
354 // is non-null.
355 bool HasOptionalArgument(size_t index);
357 // Id of this request, used to map the response back to the caller.
358 int request_id_;
360 // The id of the profile of this function's extension.
361 void* profile_id_;
363 // The extension that called this function.
364 scoped_refptr<const extensions::Extension> extension_;
366 // The name of this function.
367 const char* name_;
369 // The URL of the frame which is making this request
370 GURL source_url_;
372 // True if the js caller provides a callback function to receive the response
373 // of this call.
374 bool has_callback_;
376 // True if this callback should include information from incognito contexts
377 // even if our profile_ is non-incognito. Note that in the case of a "split"
378 // mode extension, this will always be false, and we will limit access to
379 // data from within the same profile_ (either incognito or not).
380 bool include_incognito_;
382 // True if the call was made in response of user gesture.
383 bool user_gesture_;
385 // The arguments to the API. Only non-null if argument were specified.
386 scoped_ptr<base::ListValue> args_;
388 // The results of the API. This should be populated by the derived class
389 // before SendResponse() is called.
390 scoped_ptr<base::ListValue> results_;
392 // Any detailed error from the API. This should be populated by the derived
393 // class before Run() returns.
394 std::string error_;
396 // Any class that gets a malformed message should set this to true before
397 // returning. Usually we want to kill the message sending process.
398 bool bad_message_;
400 // The sample value to record with the histogram API when the function
401 // is invoked.
402 extensions::functions::HistogramValue histogram_value_;
404 // The callback to run once the function has done execution.
405 ResponseCallback response_callback_;
407 // The ID of the tab triggered this function call, or -1 if there is no tab.
408 int source_tab_id_;
410 // The type of the JavaScript context where this call originated.
411 extensions::Feature::Context source_context_type_;
413 private:
414 void OnRespondingLater(ResponseValue response);
416 DISALLOW_COPY_AND_ASSIGN(ExtensionFunction);
419 // Extension functions that run on the UI thread. Most functions fall into
420 // this category.
421 class UIThreadExtensionFunction : public ExtensionFunction {
422 public:
423 // TODO(yzshen): We should be able to remove this interface now that we
424 // support overriding the response callback.
425 // A delegate for use in testing, to intercept the call to SendResponse.
426 class DelegateForTests {
427 public:
428 virtual void OnSendResponse(UIThreadExtensionFunction* function,
429 bool success,
430 bool bad_message) = 0;
433 UIThreadExtensionFunction();
435 UIThreadExtensionFunction* AsUIThreadExtensionFunction() override;
437 void set_test_delegate(DelegateForTests* delegate) {
438 delegate_ = delegate;
441 // Called when a message was received.
442 // Should return true if it processed the message.
443 virtual bool OnMessageReceived(const IPC::Message& message);
445 // Set the browser context which contains the extension that has originated
446 // this function call.
447 void set_browser_context(content::BrowserContext* context) {
448 context_ = context;
450 content::BrowserContext* browser_context() const { return context_; }
452 void SetRenderViewHost(content::RenderViewHost* render_view_host);
453 content::RenderViewHost* render_view_host() const {
454 return render_view_host_;
456 void SetRenderFrameHost(content::RenderFrameHost* render_frame_host);
457 content::RenderFrameHost* render_frame_host() const {
458 return render_frame_host_;
461 void set_dispatcher(const base::WeakPtr<
462 extensions::ExtensionFunctionDispatcher>& dispatcher) {
463 dispatcher_ = dispatcher;
465 extensions::ExtensionFunctionDispatcher* dispatcher() const {
466 return dispatcher_.get();
469 // Gets the "current" web contents if any. If there is no associated web
470 // contents then defaults to the foremost one.
471 virtual content::WebContents* GetAssociatedWebContents();
473 protected:
474 // Emits a message to the extension's devtools console.
475 void WriteToConsole(content::ConsoleMessageLevel level,
476 const std::string& message);
478 friend struct content::BrowserThread::DeleteOnThread<
479 content::BrowserThread::UI>;
480 friend class base::DeleteHelper<UIThreadExtensionFunction>;
482 ~UIThreadExtensionFunction() override;
484 void SendResponse(bool success) override;
486 // Sets the Blob UUIDs whose ownership is being transferred to the renderer.
487 void SetTransferredBlobUUIDs(const std::vector<std::string>& blob_uuids);
489 // The dispatcher that will service this extension function call.
490 base::WeakPtr<extensions::ExtensionFunctionDispatcher> dispatcher_;
492 // The RenderViewHost we will send responses to.
493 content::RenderViewHost* render_view_host_;
495 // The RenderFrameHost we will send responses to.
496 // NOTE: either render_view_host_ or render_frame_host_ will be set, as we
497 // port code to use RenderFrames for OOPIF. See http://crbug.com/304341.
498 content::RenderFrameHost* render_frame_host_;
500 // The content::BrowserContext of this function's extension.
501 content::BrowserContext* context_;
503 private:
504 class RenderHostTracker;
506 void Destruct() const override;
508 // TODO(tommycli): Remove once RenderViewHost is gone.
509 IPC::Sender* GetIPCSender();
510 int GetRoutingID();
512 scoped_ptr<RenderHostTracker> tracker_;
514 DelegateForTests* delegate_;
516 // The blobs transferred to the renderer process.
517 std::vector<std::string> transferred_blob_uuids_;
520 // Extension functions that run on the IO thread. This type of function avoids
521 // a roundtrip to and from the UI thread (because communication with the
522 // extension process happens on the IO thread). It's intended to be used when
523 // performance is critical (e.g. the webRequest API which can block network
524 // requests). Generally, UIThreadExtensionFunction is more appropriate and will
525 // be easier to use and interface with the rest of the browser.
526 class IOThreadExtensionFunction : public ExtensionFunction {
527 public:
528 IOThreadExtensionFunction();
530 IOThreadExtensionFunction* AsIOThreadExtensionFunction() override;
532 void set_ipc_sender(
533 base::WeakPtr<extensions::IOThreadExtensionMessageFilter> ipc_sender,
534 int routing_id) {
535 ipc_sender_ = ipc_sender;
536 routing_id_ = routing_id;
539 base::WeakPtr<extensions::IOThreadExtensionMessageFilter> ipc_sender_weak()
540 const {
541 return ipc_sender_;
544 int routing_id() const { return routing_id_; }
546 void set_extension_info_map(const extensions::InfoMap* extension_info_map) {
547 extension_info_map_ = extension_info_map;
549 const extensions::InfoMap* extension_info_map() const {
550 return extension_info_map_.get();
553 protected:
554 friend struct content::BrowserThread::DeleteOnThread<
555 content::BrowserThread::IO>;
556 friend class base::DeleteHelper<IOThreadExtensionFunction>;
558 ~IOThreadExtensionFunction() override;
560 void Destruct() const override;
562 void SendResponse(bool success) override;
564 private:
565 base::WeakPtr<extensions::IOThreadExtensionMessageFilter> ipc_sender_;
566 int routing_id_;
568 scoped_refptr<const extensions::InfoMap> extension_info_map_;
571 // Base class for an extension function that runs asynchronously *relative to
572 // the browser's UI thread*.
573 class AsyncExtensionFunction : public UIThreadExtensionFunction {
574 public:
575 AsyncExtensionFunction();
577 protected:
578 ~AsyncExtensionFunction() override;
580 // Deprecated: Override UIThreadExtensionFunction and implement Run() instead.
582 // AsyncExtensionFunctions implement this method. Return true to indicate that
583 // nothing has gone wrong yet; SendResponse must be called later. Return false
584 // to respond immediately with an error.
585 virtual bool RunAsync() = 0;
587 // ValidationFailure override to match RunAsync().
588 static bool ValidationFailure(AsyncExtensionFunction* function);
590 private:
591 ResponseAction Run() override;
594 // A SyncExtensionFunction is an ExtensionFunction that runs synchronously
595 // *relative to the browser's UI thread*. Note that this has nothing to do with
596 // running synchronously relative to the extension process. From the extension
597 // process's point of view, the function is still asynchronous.
599 // This kind of function is convenient for implementing simple APIs that just
600 // need to interact with things on the browser UI thread.
601 class SyncExtensionFunction : public UIThreadExtensionFunction {
602 public:
603 SyncExtensionFunction();
605 protected:
606 ~SyncExtensionFunction() override;
608 // Deprecated: Override UIThreadExtensionFunction and implement Run() instead.
610 // SyncExtensionFunctions implement this method. Return true to respond
611 // immediately with success, false to respond immediately with an error.
612 virtual bool RunSync() = 0;
614 // ValidationFailure override to match RunSync().
615 static bool ValidationFailure(SyncExtensionFunction* function);
617 private:
618 ResponseAction Run() override;
621 class SyncIOThreadExtensionFunction : public IOThreadExtensionFunction {
622 public:
623 SyncIOThreadExtensionFunction();
625 protected:
626 ~SyncIOThreadExtensionFunction() override;
628 // Deprecated: Override IOThreadExtensionFunction and implement Run() instead.
630 // SyncIOThreadExtensionFunctions implement this method. Return true to
631 // respond immediately with success, false to respond immediately with an
632 // error.
633 virtual bool RunSync() = 0;
635 // ValidationFailure override to match RunSync().
636 static bool ValidationFailure(SyncIOThreadExtensionFunction* function);
638 private:
639 ResponseAction Run() override;
642 #endif // EXTENSIONS_BROWSER_EXTENSION_FUNCTION_H_