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