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