- add sources.
[platform/framework/web/crosswalk.git] / src / chrome / renderer / extensions / dispatcher.h
1 // Copyright (c) 2012 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 CHROME_RENDERER_EXTENSIONS_DISPATCHER_H_
6 #define CHROME_RENDERER_EXTENSIONS_DISPATCHER_H_
7
8 #include <map>
9 #include <set>
10 #include <string>
11 #include <vector>
12
13 #include "base/memory/shared_memory.h"
14 #include "base/timer/timer.h"
15 #include "chrome/common/extensions/extension_set.h"
16 #include "chrome/renderer/extensions/chrome_v8_context.h"
17 #include "chrome/renderer/extensions/chrome_v8_context_set.h"
18 #include "chrome/renderer/extensions/v8_schema_registry.h"
19 #include "chrome/renderer/resource_bundle_source_map.h"
20 #include "content/public/renderer/render_process_observer.h"
21 #include "extensions/common/event_filter.h"
22 #include "extensions/common/extensions_client.h"
23 #include "extensions/common/features/feature.h"
24 #include "third_party/WebKit/public/platform/WebString.h"
25 #include "third_party/WebKit/public/platform/WebVector.h"
26 #include "v8/include/v8.h"
27
28 class ChromeRenderViewTest;
29 class GURL;
30 class ModuleSystem;
31 class URLPattern;
32 struct ExtensionMsg_ExternalConnectionInfo;
33 struct ExtensionMsg_Loaded_Params;
34
35 namespace WebKit {
36 class WebFrame;
37 class WebSecurityOrigin;
38 }
39
40 namespace base {
41 class DictionaryValue;
42 class ListValue;
43 }
44
45 namespace content {
46 class RenderThread;
47 }
48
49 namespace extensions {
50 class ContentWatcher;
51 class Extension;
52 class FilteredEventRouter;
53 class RequestSender;
54 class UserScriptSlave;
55 struct Message;
56
57 // Dispatches extension control messages sent to the renderer and stores
58 // renderer extension related state.
59 class Dispatcher : public content::RenderProcessObserver {
60  public:
61   Dispatcher();
62   virtual ~Dispatcher();
63
64   const std::set<std::string>& function_names() const {
65     return function_names_;
66   }
67
68   bool is_extension_process() const { return is_extension_process_; }
69   const ExtensionSet* extensions() const { return &extensions_; }
70   const ChromeV8ContextSet& v8_context_set() const {
71     return v8_context_set_;
72   }
73   UserScriptSlave* user_script_slave() {
74     return user_script_slave_.get();
75   }
76   V8SchemaRegistry* v8_schema_registry() {
77     return v8_schema_registry_.get();
78   }
79   ContentWatcher* content_watcher() {
80     return content_watcher_.get();
81   }
82   RequestSender* request_sender() {
83     return request_sender_.get();
84   }
85
86   bool IsExtensionActive(const std::string& extension_id) const;
87
88   // Finds the extension ID for the JavaScript context associated with the
89   // specified |frame| and isolated world. If |world_id| is zero, finds the
90   // extension ID associated with the main world's JavaScript context. If the
91   // JavaScript context isn't from an extension, returns empty string.
92   std::string GetExtensionID(const WebKit::WebFrame* frame, int world_id);
93
94   void DidCreateScriptContext(WebKit::WebFrame* frame,
95                               v8::Handle<v8::Context> context,
96                               int extension_group,
97                               int world_id);
98   void WillReleaseScriptContext(WebKit::WebFrame* frame,
99                                 v8::Handle<v8::Context> context,
100                                 int world_id);
101
102   void DidCreateDocumentElement(WebKit::WebFrame* frame);
103
104   void DidMatchCSS(
105       WebKit::WebFrame* frame,
106       const WebKit::WebVector<WebKit::WebString>& newly_matching_selectors,
107       const WebKit::WebVector<WebKit::WebString>& stopped_matching_selectors);
108
109   // TODO(mpcomplete): remove. http://crbug.com/100411
110   bool IsAdblockWithWebRequestInstalled() const {
111     return webrequest_adblock_;
112   }
113   bool IsAdblockPlusWithWebRequestInstalled() const {
114     return webrequest_adblock_plus_;
115   }
116   bool IsOtherExtensionWithWebRequestInstalled() const {
117     return webrequest_other_;
118   }
119
120   void OnExtensionResponse(int request_id,
121                            bool success,
122                            const base::ListValue& response,
123                            const std::string& error);
124
125   // Checks that the current context contains an extension that has permission
126   // to execute the specified function. If it does not, a v8 exception is thrown
127   // and the method returns false. Otherwise returns true.
128   bool CheckContextAccessToExtensionAPI(
129       const std::string& function_name, ChromeV8Context* context) const;
130
131   // Dispatches the event named |event_name| to all render views.
132   void DispatchEvent(const std::string& extension_id,
133                      const std::string& event_name) const;
134
135   // Shared implementation of the various MessageInvoke IPCs.
136   void InvokeModuleSystemMethod(
137       content::RenderView* render_view,
138       const std::string& extension_id,
139       const std::string& module_name,
140       const std::string& function_name,
141       const base::ListValue& args,
142       bool user_gesture);
143
144  private:
145   friend class ::ChromeRenderViewTest;
146   FRIEND_TEST_ALL_PREFIXES(RendererPermissionsPolicyDelegateTest,
147                            CannotScriptWebstore);
148   typedef void (*BindingInstaller)(ModuleSystem* module_system,
149                                   v8::Handle<v8::Object> chrome);
150
151   // RenderProcessObserver implementation:
152   virtual bool OnControlMessageReceived(const IPC::Message& message) OVERRIDE;
153   virtual void WebKitInitialized() OVERRIDE;
154   virtual void IdleNotification() OVERRIDE;
155   virtual void OnRenderProcessShutdown() OVERRIDE;
156
157   void OnSetChannel(int channel);
158   void OnMessageInvoke(const std::string& extension_id,
159                        const std::string& module_name,
160                        const std::string& function_name,
161                        const base::ListValue& args,
162                        bool user_gesture);
163   void OnDispatchOnConnect(int target_port_id,
164                            const std::string& channel_name,
165                            const base::DictionaryValue& source_tab,
166                            const ExtensionMsg_ExternalConnectionInfo& info,
167                            const std::string& tls_channel_id);
168   void OnDeliverMessage(int target_port_id, const Message& message);
169   void OnDispatchOnDisconnect(int port_id, const std::string& error_message);
170   void OnSetFunctionNames(const std::vector<std::string>& names);
171   void OnSetSystemFont(const std::string& font_family,
172                        const std::string& font_size);
173   void OnLoaded(
174       const std::vector<ExtensionMsg_Loaded_Params>& loaded_extensions);
175   void OnLoadedInternal(scoped_refptr<const Extension> extension);
176   void OnUnloaded(const std::string& id);
177   void OnSetScriptingWhitelist(
178       const ExtensionsClient::ScriptingWhitelist& extension_ids);
179   void OnPageActionsUpdated(const std::string& extension_id,
180       const std::vector<std::string>& page_actions);
181   void OnActivateExtension(const std::string& extension_id);
182   void OnUpdatePermissions(int reason_id,
183                            const std::string& extension_id,
184                            const APIPermissionSet& apis,
185                            const URLPatternSet& explicit_hosts,
186                            const URLPatternSet& scriptable_hosts);
187   void OnUpdateTabSpecificPermissions(int page_id,
188                                       int tab_id,
189                                       const std::string& extension_id,
190                                       const URLPatternSet& origin_set);
191   void OnClearTabSpecificPermissions(
192       int tab_id,
193       const std::vector<std::string>& extension_ids);
194   void OnUpdateUserScripts(base::SharedMemoryHandle table);
195   void OnUsingWebRequestAPI(
196       bool adblock,
197       bool adblock_plus,
198       bool other_webrequest);
199   void OnShouldSuspend(const std::string& extension_id, int sequence_id);
200   void OnSuspend(const std::string& extension_id);
201   void OnCancelSuspend(const std::string& extension_id);
202
203   // Update the list of active extensions that will be reported when we crash.
204   void UpdateActiveExtensions();
205
206   // Sets up the host permissions for |extension|.
207   void InitOriginPermissions(const Extension* extension);
208   void AddOrRemoveOriginPermissions(
209       UpdatedExtensionPermissionsInfo::Reason reason,
210       const Extension* extension,
211       const URLPatternSet& origins);
212
213   // Enable custom element whitelist in Apps.
214   void EnableCustomElementWhiteList();
215
216   // Adds or removes bindings for every context belonging to |extension_id|, or
217   // or all contexts if |extension_id| is empty.
218   void AddOrRemoveBindings(const std::string& extension_id);
219
220   void RegisterNativeHandlers(ModuleSystem* module_system,
221                               ChromeV8Context* context);
222   void AddOrRemoveBindingsForContext(ChromeV8Context* context);
223   void RegisterBinding(const std::string& api_name,
224                        ChromeV8Context* context);
225   v8::Handle<v8::Object> GetOrCreateBindObjectIfAvailable(
226       const std::string& api_name,
227       std::string* bind_name,
228       ChromeV8Context* context);
229
230   // Inserts static source code into |source_map_|.
231   void PopulateSourceMap();
232
233   // Inserts BindingInstallers into |lazy_bindings_map_|.
234   void PopulateLazyBindingsMap();
235
236   // Sets up the bindings for the given api.
237   void InstallBindings(ModuleSystem* module_system,
238                        v8::Handle<v8::Context> v8_context,
239                        const std::string& api);
240
241   // Returns whether the current renderer hosts a platform app.
242   bool IsWithinPlatformApp();
243
244   bool IsSandboxedPage(const GURL& url) const;
245
246   // Returns the Feature::Context type of context for a JavaScript context.
247   Feature::Context ClassifyJavaScriptContext(
248       const std::string& extension_id,
249       int extension_group,
250       const GURL& url,
251       const WebKit::WebSecurityOrigin& origin);
252
253   // Gets |field| from |object| or creates it as an empty object if it doesn't
254   // exist.
255   v8::Handle<v8::Object> GetOrCreateObject(v8::Handle<v8::Object> object,
256                                            const std::string& field);
257
258   // True if this renderer is running extensions.
259   bool is_extension_process_;
260
261   // Contains all loaded extensions.  This is essentially the renderer
262   // counterpart to ExtensionService in the browser. It contains information
263   // about all extensions currently loaded by the browser.
264   ExtensionSet extensions_;
265
266   // The IDs of extensions that failed to load, mapped to the error message
267   // generated on failure.
268   std::map<std::string, std::string> extension_load_errors_;
269
270   // All the bindings contexts that are currently loaded for this renderer.
271   // There is zero or one for each v8 context.
272   ChromeV8ContextSet v8_context_set_;
273
274   scoped_ptr<UserScriptSlave> user_script_slave_;
275
276   scoped_ptr<ContentWatcher> content_watcher_;
277
278   // Same as above, but on a longer timer and will run even if the process is
279   // not idle, to ensure that IdleHandle gets called eventually.
280   base::RepeatingTimer<content::RenderThread> forced_idle_timer_;
281
282   // All declared function names.
283   std::set<std::string> function_names_;
284
285   // The extensions and apps that are active in this process.
286   std::set<std::string> active_extension_ids_;
287
288   // True once WebKit has been initialized (and it is therefore safe to poke).
289   bool is_webkit_initialized_;
290
291   // Status of webrequest usage for known extensions.
292   // TODO(mpcomplete): remove. http://crbug.com/100411
293   bool webrequest_adblock_;
294   bool webrequest_adblock_plus_;
295   bool webrequest_other_;
296
297   ResourceBundleSourceMap source_map_;
298
299   // Cache for the v8 representation of extension API schemas.
300   scoped_ptr<V8SchemaRegistry> v8_schema_registry_;
301
302   // Bindings that are defined lazily and have BindingInstallers to install
303   // them.
304   std::map<std::string, BindingInstaller> lazy_bindings_map_;
305
306   // Sends API requests to the extension host.
307   scoped_ptr<RequestSender> request_sender_;
308
309   // The platforms system font family and size;
310   std::string system_font_family_;
311   std::string system_font_size_;
312
313   DISALLOW_COPY_AND_ASSIGN(Dispatcher);
314 };
315
316 }  // namespace extensions
317
318 #endif  // CHROME_RENDERER_EXTENSIONS_DISPATCHER_H_