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.
4
5#ifndef EXTENSIONS_BROWSER_EXTENSION_FUNCTION_H_
6#define EXTENSIONS_BROWSER_EXTENSION_FUNCTION_H_
7
8#include <list>
9#include <string>
10
11#include "base/callback.h"
12#include "base/compiler_specific.h"
13#include "base/memory/ref_counted.h"
14#include "base/memory/scoped_ptr.h"
15#include "base/memory/weak_ptr.h"
16#include "base/process/process.h"
17#include "base/sequenced_task_runner_helpers.h"
18#include "content/public/browser/browser_thread.h"
19#include "content/public/common/console_message_level.h"
20#include "extensions/browser/extension_function_histogram_value.h"
21#include "extensions/browser/info_map.h"
22#include "extensions/common/extension.h"
23#include "ipc/ipc_message.h"
24
25class ExtensionFunction;
26class UIThreadExtensionFunction;
27class IOThreadExtensionFunction;
28
29namespace base {
30class ListValue;
31class Value;
32}
33
34namespace content {
35class BrowserContext;
36class RenderFrameHost;
37class RenderViewHost;
38class WebContents;
39}
40
41namespace extensions {
42class ExtensionFunctionDispatcher;
43class ExtensionMessageFilter;
44class QuotaLimitHeuristic;
45}
46
47namespace IPC {
48class Sender;
49}
50
51#ifdef NDEBUG
52#define EXTENSION_FUNCTION_VALIDATE(test) \
53  do {                                    \
54    if (!(test)) {                        \
55      bad_message_ = true;                \
56      return ValidationFailure(this);     \
57    }                                     \
58  } while (0)
59#else   // NDEBUG
60#define EXTENSION_FUNCTION_VALIDATE(test) CHECK(test)
61#endif  // NDEBUG
62
63#define EXTENSION_FUNCTION_ERROR(error) \
64  do {                                  \
65    error_ = error;                     \
66    bad_message_ = true;                \
67    return ValidationFailure(this);     \
68  } while (0)
69
70// Declares a callable extension function with the given |name|. You must also
71// supply a unique |histogramvalue| used for histograms of extension function
72// invocation (add new ones at the end of the enum in
73// extension_function_histogram_value.h).
74#define DECLARE_EXTENSION_FUNCTION(name, histogramvalue) \
75  public: static const char* function_name() { return name; } \
76  public: static extensions::functions::HistogramValue histogram_value() \
77    { return extensions::functions::histogramvalue; }
78
79// Traits that describe how ExtensionFunction should be deleted. This just calls
80// the virtual "Destruct" method on ExtensionFunction, allowing derived classes
81// to override the behavior.
82struct ExtensionFunctionDeleteTraits {
83 public:
84  static void Destruct(const ExtensionFunction* x);
85};
86
87// Abstract base class for extension functions the ExtensionFunctionDispatcher
88// knows how to dispatch to.
89class ExtensionFunction
90    : public base::RefCountedThreadSafe<ExtensionFunction,
91                                        ExtensionFunctionDeleteTraits> {
92 public:
93  enum ResponseType {
94    // The function has succeeded.
95    SUCCEEDED,
96    // The function has failed.
97    FAILED,
98    // The input message is malformed.
99    BAD_MESSAGE
100  };
101
102  typedef base::Callback<void(ResponseType type,
103                              const base::ListValue& results,
104                              const std::string& error)> ResponseCallback;
105
106  ExtensionFunction();
107
108  virtual UIThreadExtensionFunction* AsUIThreadExtensionFunction();
109  virtual IOThreadExtensionFunction* AsIOThreadExtensionFunction();
110
111  // Returns true if the function has permission to run.
112  //
113  // The default implementation is to check the Extension's permissions against
114  // what this function requires to run, but some APIs may require finer
115  // grained control, such as tabs.executeScript being allowed for active tabs.
116  //
117  // This will be run after the function has been set up but before Run().
118  virtual bool HasPermission();
119
120  // The result of a function call.
121  //
122  // Use NoArguments(), OneArgument(), ArgumentList(), or Error()
123  // rather than this class directly.
124  class ResponseValueObject {
125   public:
126    virtual ~ResponseValueObject() {}
127
128    // Returns true for success, false for failure.
129    virtual bool Apply() = 0;
130  };
131  typedef scoped_ptr<ResponseValueObject> ResponseValue;
132
133  // The action to use when returning from RunAsync.
134  //
135  // Use RespondNow() or RespondLater() rather than this class directly.
136  class ResponseActionObject {
137   public:
138    virtual ~ResponseActionObject() {}
139
140    virtual void Execute() = 0;
141  };
142  typedef scoped_ptr<ResponseActionObject> ResponseAction;
143
144  // Runs the function and returns the action to take when the caller is ready
145  // to respond.
146  //
147  // Typical return values might be:
148  //   * RespondNow(NoArguments())
149  //   * RespondNow(OneArgument(42))
150  //   * RespondNow(ArgumentList(my_result.ToValue()))
151  //   * RespondNow(Error("Warp core breach"))
152  //   * RespondNow(Error("Warp core breach on *", GetURL()))
153  //   * RespondLater(), then later,
154  //     * Respond(NoArguments())
155  //     * ... etc.
156  //
157  //
158  // Callers must call Execute() on the return ResponseAction at some point,
159  // exactly once.
160  //
161  // SyncExtensionFunction and AsyncExtensionFunction implement this in terms
162  // of SyncExtensionFunction::RunSync and AsyncExtensionFunction::RunAsync,
163  // but this is deprecated. ExtensionFunction implementations are encouraged
164  // to just implement Run.
165  virtual ResponseAction Run() WARN_UNUSED_RESULT = 0;
166
167  // Gets whether quota should be applied to this individual function
168  // invocation. This is different to GetQuotaLimitHeuristics which is only
169  // invoked once and then cached.
170  //
171  // Returns false by default.
172  virtual bool ShouldSkipQuotaLimiting() const;
173
174  // Optionally adds one or multiple QuotaLimitHeuristic instances suitable for
175  // this function to |heuristics|. The ownership of the new QuotaLimitHeuristic
176  // instances is passed to the owner of |heuristics|.
177  // No quota limiting by default.
178  //
179  // Only called once per lifetime of the QuotaService.
180  virtual void GetQuotaLimitHeuristics(
181      extensions::QuotaLimitHeuristics* heuristics) const {}
182
183  // Called when the quota limit has been exceeded. The default implementation
184  // returns an error.
185  virtual void OnQuotaExceeded(const std::string& violation_error);
186
187  // Specifies the raw arguments to the function, as a JSON value.
188  virtual void SetArgs(const base::ListValue* args);
189
190  // Sets a single Value as the results of the function.
191  void SetResult(base::Value* result);
192
193  // Sets multiple Values as the results of the function.
194  void SetResultList(scoped_ptr<base::ListValue> results);
195
196  // Retrieves the results of the function as a ListValue.
197  const base::ListValue* GetResultList() const;
198
199  // Retrieves any error string from the function.
200  virtual std::string GetError() const;
201
202  // Sets the function's error string.
203  virtual void SetError(const std::string& error);
204
205  // Sets the function's bad message state.
206  void set_bad_message(bool bad_message) { bad_message_ = bad_message; }
207
208  // Specifies the name of the function.
209  void set_name(const std::string& name) { name_ = name; }
210  const std::string& name() const { return name_; }
211
212  void set_profile_id(void* profile_id) { profile_id_ = profile_id; }
213  void* profile_id() const { return profile_id_; }
214
215  void set_extension(const extensions::Extension* extension) {
216    extension_ = extension;
217  }
218  const extensions::Extension* GetExtension() const { return extension_.get(); }
219  const std::string& extension_id() const { return extension_->id(); }
220
221  void set_request_id(int request_id) { request_id_ = request_id; }
222  int request_id() { return request_id_; }
223
224  void set_source_url(const GURL& source_url) { source_url_ = source_url; }
225  const GURL& source_url() { return source_url_; }
226
227  void set_has_callback(bool has_callback) { has_callback_ = has_callback; }
228  bool has_callback() { return has_callback_; }
229
230  void set_include_incognito(bool include) { include_incognito_ = include; }
231  bool include_incognito() const { return include_incognito_; }
232
233  void set_user_gesture(bool user_gesture) { user_gesture_ = user_gesture; }
234  bool user_gesture() const { return user_gesture_; }
235
236  void set_histogram_value(
237      extensions::functions::HistogramValue histogram_value) {
238    histogram_value_ = histogram_value; }
239  extensions::functions::HistogramValue histogram_value() const {
240    return histogram_value_; }
241
242  void set_response_callback(const ResponseCallback& callback) {
243    response_callback_ = callback;
244  }
245
246  void set_source_tab_id(int source_tab_id) { source_tab_id_ = source_tab_id; }
247  int source_tab_id() const { return source_tab_id_; }
248
249 protected:
250  friend struct ExtensionFunctionDeleteTraits;
251
252  // ResponseValues.
253  //
254  // Success, no arguments to pass to caller
255  ResponseValue NoArguments();
256  // Success, a single argument |arg| to pass to caller. TAKES OWNERSHIP -- a
257  // raw pointer for convenience, since callers usually construct the argument
258  // to this by hand.
259  ResponseValue OneArgument(base::Value* arg);
260  // Success, two arguments |arg1| and |arg2| to pass to caller. TAKES
261  // OWNERSHIP -- raw pointers for convenience, since callers usually construct
262  // the argument to this by hand. Note that use of this function may imply you
263  // should be using the generated Result struct and ArgumentList.
264  ResponseValue TwoArguments(base::Value* arg1, base::Value* arg2);
265  // Success, a list of arguments |results| to pass to caller. TAKES OWNERSHIP
266  // --
267  // a scoped_ptr<> for convenience, since callers usually get this from the
268  // result of a ToValue() call on the generated Result struct.
269  ResponseValue ArgumentList(scoped_ptr<base::ListValue> results);
270  // Error. chrome.runtime.lastError.message will be set to |error|.
271  ResponseValue Error(const std::string& error);
272  // Error with formatting. Args are processed using
273  // ErrorUtils::FormatErrorMessage, that is, each occurence of * is replaced
274  // by the corresponding |s*|:
275  // Error("Error in *: *", "foo", "bar") <--> // Error("Error in foo: bar").
276  ResponseValue Error(const std::string& format, const std::string& s1);
277  ResponseValue Error(const std::string& format,
278                      const std::string& s1,
279                      const std::string& s2);
280  ResponseValue Error(const std::string& format,
281                      const std::string& s1,
282                      const std::string& s2,
283                      const std::string& s3);
284  // Bad message. A ResponseValue equivalent to EXTENSION_FUNCTION_VALIDATE().
285  ResponseValue BadMessage();
286
287  // ResponseActions.
288  //
289  // Respond to the extension immediately with |result|.
290  ResponseAction RespondNow(ResponseValue result);
291  // Don't respond now, but promise to call Respond() later.
292  ResponseAction RespondLater();
293
294  // This is the return value of the EXTENSION_FUNCTION_VALIDATE macro, which
295  // needs to work from Run(), RunAsync(), and RunSync(). The former of those
296  // has a different return type (ResponseAction) than the latter two (bool).
297  static ResponseAction ValidationFailure(ExtensionFunction* function);
298
299  // If RespondLater() was used, functions must at some point call Respond()
300  // with |result| as their result.
301  void Respond(ResponseValue result);
302
303  virtual ~ExtensionFunction();
304
305  // Helper method for ExtensionFunctionDeleteTraits. Deletes this object.
306  virtual void Destruct() const = 0;
307
308  // Do not call this function directly, return the appropriate ResponseAction
309  // from Run() instead. If using RespondLater then call Respond().
310  //
311  // Call with true to indicate success, false to indicate failure, in which
312  // case please set |error_|.
313  virtual void SendResponse(bool success) = 0;
314
315  // Common implementation for SendResponse.
316  void SendResponseImpl(bool success);
317
318  // Return true if the argument to this function at |index| was provided and
319  // is non-null.
320  bool HasOptionalArgument(size_t index);
321
322  // Id of this request, used to map the response back to the caller.
323  int request_id_;
324
325  // The id of the profile of this function's extension.
326  void* profile_id_;
327
328  // The extension that called this function.
329  scoped_refptr<const extensions::Extension> extension_;
330
331  // The name of this function.
332  std::string name_;
333
334  // The URL of the frame which is making this request
335  GURL source_url_;
336
337  // True if the js caller provides a callback function to receive the response
338  // of this call.
339  bool has_callback_;
340
341  // True if this callback should include information from incognito contexts
342  // even if our profile_ is non-incognito. Note that in the case of a "split"
343  // mode extension, this will always be false, and we will limit access to
344  // data from within the same profile_ (either incognito or not).
345  bool include_incognito_;
346
347  // True if the call was made in response of user gesture.
348  bool user_gesture_;
349
350  // The arguments to the API. Only non-null if argument were specified.
351  scoped_ptr<base::ListValue> args_;
352
353  // The results of the API. This should be populated by the derived class
354  // before SendResponse() is called.
355  scoped_ptr<base::ListValue> results_;
356
357  // Any detailed error from the API. This should be populated by the derived
358  // class before Run() returns.
359  std::string error_;
360
361  // Any class that gets a malformed message should set this to true before
362  // returning.  Usually we want to kill the message sending process.
363  bool bad_message_;
364
365  // The sample value to record with the histogram API when the function
366  // is invoked.
367  extensions::functions::HistogramValue histogram_value_;
368
369  // The callback to run once the function has done execution.
370  ResponseCallback response_callback_;
371
372  // The ID of the tab triggered this function call, or -1 if there is no tab.
373  int source_tab_id_;
374
375 private:
376  void OnRespondingLater(ResponseValue response);
377
378  DISALLOW_COPY_AND_ASSIGN(ExtensionFunction);
379};
380
381// Extension functions that run on the UI thread. Most functions fall into
382// this category.
383class UIThreadExtensionFunction : public ExtensionFunction {
384 public:
385  // TODO(yzshen): We should be able to remove this interface now that we
386  // support overriding the response callback.
387  // A delegate for use in testing, to intercept the call to SendResponse.
388  class DelegateForTests {
389   public:
390    virtual void OnSendResponse(UIThreadExtensionFunction* function,
391                                bool success,
392                                bool bad_message) = 0;
393  };
394
395  UIThreadExtensionFunction();
396
397  virtual UIThreadExtensionFunction* AsUIThreadExtensionFunction() OVERRIDE;
398
399  void set_test_delegate(DelegateForTests* delegate) {
400    delegate_ = delegate;
401  }
402
403  // Called when a message was received.
404  // Should return true if it processed the message.
405  virtual bool OnMessageReceived(const IPC::Message& message);
406
407  // Set the browser context which contains the extension that has originated
408  // this function call.
409  void set_browser_context(content::BrowserContext* context) {
410    context_ = context;
411  }
412  content::BrowserContext* browser_context() const { return context_; }
413
414  void SetRenderViewHost(content::RenderViewHost* render_view_host);
415  content::RenderViewHost* render_view_host() const {
416    return render_view_host_;
417  }
418  void SetRenderFrameHost(content::RenderFrameHost* render_frame_host);
419  content::RenderFrameHost* render_frame_host() const {
420    return render_frame_host_;
421  }
422
423  void set_dispatcher(const base::WeakPtr<
424      extensions::ExtensionFunctionDispatcher>& dispatcher) {
425    dispatcher_ = dispatcher;
426  }
427  extensions::ExtensionFunctionDispatcher* dispatcher() const {
428    return dispatcher_.get();
429  }
430
431  // Gets the "current" web contents if any. If there is no associated web
432  // contents then defaults to the foremost one.
433  virtual content::WebContents* GetAssociatedWebContents();
434
435 protected:
436  // Emits a message to the extension's devtools console.
437  void WriteToConsole(content::ConsoleMessageLevel level,
438                      const std::string& message);
439
440  friend struct content::BrowserThread::DeleteOnThread<
441      content::BrowserThread::UI>;
442  friend class base::DeleteHelper<UIThreadExtensionFunction>;
443
444  virtual ~UIThreadExtensionFunction();
445
446  virtual void SendResponse(bool success) OVERRIDE;
447
448  // Sets the Blob UUIDs whose ownership is being transferred to the renderer.
449  void SetTransferredBlobUUIDs(const std::vector<std::string>& blob_uuids);
450
451  // The dispatcher that will service this extension function call.
452  base::WeakPtr<extensions::ExtensionFunctionDispatcher> dispatcher_;
453
454  // The RenderViewHost we will send responses to.
455  content::RenderViewHost* render_view_host_;
456
457  // The RenderFrameHost we will send responses to.
458  // NOTE: either render_view_host_ or render_frame_host_ will be set, as we
459  // port code to use RenderFrames for OOPIF. See http://crbug.com/304341.
460  content::RenderFrameHost* render_frame_host_;
461
462  // The content::BrowserContext of this function's extension.
463  content::BrowserContext* context_;
464
465 private:
466  class RenderHostTracker;
467
468  virtual void Destruct() const OVERRIDE;
469
470  // TODO(tommycli): Remove once RenderViewHost is gone.
471  IPC::Sender* GetIPCSender();
472  int GetRoutingID();
473
474  scoped_ptr<RenderHostTracker> tracker_;
475
476  DelegateForTests* delegate_;
477
478  // The blobs transferred to the renderer process.
479  std::vector<std::string> transferred_blob_uuids_;
480};
481
482// Extension functions that run on the IO thread. This type of function avoids
483// a roundtrip to and from the UI thread (because communication with the
484// extension process happens on the IO thread). It's intended to be used when
485// performance is critical (e.g. the webRequest API which can block network
486// requests). Generally, UIThreadExtensionFunction is more appropriate and will
487// be easier to use and interface with the rest of the browser.
488class IOThreadExtensionFunction : public ExtensionFunction {
489 public:
490  IOThreadExtensionFunction();
491
492  virtual IOThreadExtensionFunction* AsIOThreadExtensionFunction() OVERRIDE;
493
494  void set_ipc_sender(
495      base::WeakPtr<extensions::ExtensionMessageFilter> ipc_sender,
496      int routing_id) {
497    ipc_sender_ = ipc_sender;
498    routing_id_ = routing_id;
499  }
500
501  base::WeakPtr<extensions::ExtensionMessageFilter> ipc_sender_weak() const {
502    return ipc_sender_;
503  }
504
505  int routing_id() const { return routing_id_; }
506
507  void set_extension_info_map(const extensions::InfoMap* extension_info_map) {
508    extension_info_map_ = extension_info_map;
509  }
510  const extensions::InfoMap* extension_info_map() const {
511    return extension_info_map_.get();
512  }
513
514 protected:
515  friend struct content::BrowserThread::DeleteOnThread<
516      content::BrowserThread::IO>;
517  friend class base::DeleteHelper<IOThreadExtensionFunction>;
518
519  virtual ~IOThreadExtensionFunction();
520
521  virtual void Destruct() const OVERRIDE;
522
523  virtual void SendResponse(bool success) OVERRIDE;
524
525 private:
526  base::WeakPtr<extensions::ExtensionMessageFilter> ipc_sender_;
527  int routing_id_;
528
529  scoped_refptr<const extensions::InfoMap> extension_info_map_;
530};
531
532// Base class for an extension function that runs asynchronously *relative to
533// the browser's UI thread*.
534class AsyncExtensionFunction : public UIThreadExtensionFunction {
535 public:
536  AsyncExtensionFunction();
537
538 protected:
539  virtual ~AsyncExtensionFunction();
540
541  // Deprecated: Override UIThreadExtensionFunction and implement Run() instead.
542  //
543  // AsyncExtensionFunctions implement this method. Return true to indicate that
544  // nothing has gone wrong yet; SendResponse must be called later. Return true
545  // to respond immediately with an error.
546  virtual bool RunAsync() = 0;
547
548  // ValidationFailure override to match RunAsync().
549  static bool ValidationFailure(AsyncExtensionFunction* function);
550
551 private:
552  virtual ResponseAction Run() OVERRIDE;
553};
554
555// A SyncExtensionFunction is an ExtensionFunction that runs synchronously
556// *relative to the browser's UI thread*. Note that this has nothing to do with
557// running synchronously relative to the extension process. From the extension
558// process's point of view, the function is still asynchronous.
559//
560// This kind of function is convenient for implementing simple APIs that just
561// need to interact with things on the browser UI thread.
562class SyncExtensionFunction : public UIThreadExtensionFunction {
563 public:
564  SyncExtensionFunction();
565
566 protected:
567  virtual ~SyncExtensionFunction();
568
569  // Deprecated: Override UIThreadExtensionFunction and implement Run() instead.
570  //
571  // SyncExtensionFunctions implement this method. Return true to respond
572  // immediately with success, false to respond immediately with an error.
573  virtual bool RunSync() = 0;
574
575  // ValidationFailure override to match RunSync().
576  static bool ValidationFailure(SyncExtensionFunction* function);
577
578 private:
579  virtual ResponseAction Run() OVERRIDE;
580};
581
582class SyncIOThreadExtensionFunction : public IOThreadExtensionFunction {
583 public:
584  SyncIOThreadExtensionFunction();
585
586 protected:
587  virtual ~SyncIOThreadExtensionFunction();
588
589  // Deprecated: Override IOThreadExtensionFunction and implement Run() instead.
590  //
591  // SyncIOThreadExtensionFunctions implement this method. Return true to
592  // respond immediately with success, false to respond immediately with an
593  // error.
594  virtual bool RunSync() = 0;
595
596  // ValidationFailure override to match RunSync().
597  static bool ValidationFailure(SyncIOThreadExtensionFunction* function);
598
599 private:
600  virtual ResponseAction Run() OVERRIDE;
601};
602
603#endif  // EXTENSIONS_BROWSER_EXTENSION_FUNCTION_H_
604