Upstream version 9.38.198.0
[platform/framework/web/crosswalk.git] / src / extensions / renderer / dispatcher.h
1 // Copyright 2014 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_RENDERER_DISPATCHER_H_
6 #define EXTENSIONS_RENDERER_DISPATCHER_H_
7
8 #include <map>
9 #include <set>
10 #include <string>
11 #include <utility>
12 #include <vector>
13
14 #include "base/scoped_observer.h"
15 #include "base/timer/timer.h"
16 #include "content/public/renderer/render_process_observer.h"
17 #include "extensions/common/event_filter.h"
18 #include "extensions/common/extension_set.h"
19 #include "extensions/common/extensions_client.h"
20 #include "extensions/common/features/feature.h"
21 #include "extensions/renderer/resource_bundle_source_map.h"
22 #include "extensions/renderer/script_context.h"
23 #include "extensions/renderer/script_context_set.h"
24 #include "extensions/renderer/user_script_set_manager.h"
25 #include "extensions/renderer/v8_schema_registry.h"
26 #include "third_party/WebKit/public/platform/WebString.h"
27 #include "third_party/WebKit/public/platform/WebVector.h"
28 #include "v8/include/v8.h"
29
30 class ChromeRenderViewTest;
31 class GURL;
32 class ModuleSystem;
33 class URLPattern;
34 struct ExtensionMsg_ExternalConnectionInfo;
35 struct ExtensionMsg_Loaded_Params;
36 struct ExtensionMsg_UpdatePermissions_Params;
37
38 namespace blink {
39 class WebFrame;
40 class WebSecurityOrigin;
41 }
42
43 namespace base {
44 class DictionaryValue;
45 class ListValue;
46 }
47
48 namespace content {
49 class RenderThread;
50 }
51
52 namespace extensions {
53 class ContentWatcher;
54 class DispatcherDelegate;
55 class Extension;
56 class FilteredEventRouter;
57 class ManifestPermissionSet;
58 class RequestSender;
59 class ScriptContext;
60 class ScriptInjectionManager;
61 struct Message;
62
63 // Dispatches extension control messages sent to the renderer and stores
64 // renderer extension related state.
65 class Dispatcher : public content::RenderProcessObserver,
66                    public UserScriptSetManager::Observer {
67  public:
68   explicit Dispatcher(DispatcherDelegate* delegate);
69   virtual ~Dispatcher();
70
71   const std::set<std::string>& function_names() const {
72     return function_names_;
73   }
74
75   bool is_extension_process() const { return is_extension_process_; }
76
77   const ExtensionSet* extensions() const { return &extensions_; }
78
79   const ScriptContextSet& script_context_set() const {
80     return script_context_set_;
81   }
82
83   V8SchemaRegistry* v8_schema_registry() { return v8_schema_registry_.get(); }
84
85   ContentWatcher* content_watcher() { return content_watcher_.get(); }
86
87   RequestSender* request_sender() { return request_sender_.get(); }
88
89   void OnRenderViewCreated(content::RenderView* render_view);
90
91   bool IsExtensionActive(const std::string& extension_id) const;
92
93   // Finds the extension ID for the JavaScript context associated with the
94   // specified |frame| and isolated world. If |world_id| is zero, finds the
95   // extension ID associated with the main world's JavaScript context. If the
96   // JavaScript context isn't from an extension, returns empty string.
97   std::string GetExtensionID(const blink::WebFrame* frame, int world_id);
98
99   void DidCreateScriptContext(blink::WebFrame* frame,
100                               const v8::Handle<v8::Context>& context,
101                               int extension_group,
102                               int world_id);
103
104   void WillReleaseScriptContext(blink::WebFrame* frame,
105                                 const v8::Handle<v8::Context>& context,
106                                 int world_id);
107
108   void DidCreateDocumentElement(blink::WebFrame* frame);
109
110   void DidMatchCSS(
111       blink::WebFrame* frame,
112       const blink::WebVector<blink::WebString>& newly_matching_selectors,
113       const blink::WebVector<blink::WebString>& stopped_matching_selectors);
114
115   void OnExtensionResponse(int request_id,
116                            bool success,
117                            const base::ListValue& response,
118                            const std::string& error);
119
120   // Checks that the current context contains an extension that has permission
121   // to execute the specified function. If it does not, a v8 exception is thrown
122   // and the method returns false. Otherwise returns true.
123   bool CheckContextAccessToExtensionAPI(const std::string& function_name,
124                                         ScriptContext* context) const;
125
126   // Dispatches the event named |event_name| to all render views.
127   void DispatchEvent(const std::string& extension_id,
128                      const std::string& event_name) const;
129
130   // Shared implementation of the various MessageInvoke IPCs.
131   void InvokeModuleSystemMethod(content::RenderView* render_view,
132                                 const std::string& extension_id,
133                                 const std::string& module_name,
134                                 const std::string& function_name,
135                                 const base::ListValue& args,
136                                 bool user_gesture);
137
138   void ClearPortData(int port_id);
139
140   // Returns a list of (module name, resource id) pairs for the JS modules to
141   // add to the source map.
142   static std::vector<std::pair<std::string, int> > GetJsResources();
143   static void RegisterNativeHandlers(ModuleSystem* module_system,
144                                      ScriptContext* context,
145                                      Dispatcher* dispatcher,
146                                      RequestSender* request_sender,
147                                      V8SchemaRegistry* v8_schema_registry);
148
149  private:
150   friend class ::ChromeRenderViewTest;
151   FRIEND_TEST_ALL_PREFIXES(RendererPermissionsPolicyDelegateTest,
152                            CannotScriptWebstore);
153
154   // RenderProcessObserver implementation:
155   virtual bool OnControlMessageReceived(const IPC::Message& message) OVERRIDE;
156   virtual void WebKitInitialized() OVERRIDE;
157   virtual void IdleNotification() OVERRIDE;
158   virtual void OnRenderProcessShutdown() OVERRIDE;
159
160   void OnActivateExtension(const std::string& extension_id);
161   void OnCancelSuspend(const std::string& extension_id);
162   void OnClearTabSpecificPermissions(
163       int tab_id,
164       const std::vector<std::string>& extension_ids);
165   void OnDeliverMessage(int target_port_id, const Message& message);
166   void OnDispatchOnConnect(int target_port_id,
167                            const std::string& channel_name,
168                            const base::DictionaryValue& source_tab,
169                            const ExtensionMsg_ExternalConnectionInfo& info,
170                            const std::string& tls_channel_id);
171   void OnDispatchOnDisconnect(int port_id, const std::string& error_message);
172   void OnLoaded(
173       const std::vector<ExtensionMsg_Loaded_Params>& loaded_extensions);
174   void OnLoadedInternal(scoped_refptr<const Extension> extension);
175   void OnMessageInvoke(const std::string& extension_id,
176                        const std::string& module_name,
177                        const std::string& function_name,
178                        const base::ListValue& args,
179                        bool user_gesture);
180   void OnSetChannel(int channel);
181   void OnSetFunctionNames(const std::vector<std::string>& names);
182   void OnSetScriptingWhitelist(
183       const ExtensionsClient::ScriptingWhitelist& extension_ids);
184   void OnSetSystemFont(const std::string& font_family,
185                        const std::string& font_size);
186   void OnShouldSuspend(const std::string& extension_id, uint64 sequence_id);
187   void OnSuspend(const std::string& extension_id);
188   void OnTransferBlobs(const std::vector<std::string>& blob_uuids);
189   void OnUnloaded(const std::string& id);
190   void OnUpdatePermissions(const ExtensionMsg_UpdatePermissions_Params& params);
191   void OnUpdateTabSpecificPermissions(const GURL& url,
192                                       int tab_id,
193                                       const std::string& extension_id,
194                                       const URLPatternSet& origin_set);
195   void OnUsingWebRequestAPI(bool webrequest_used);
196
197   // UserScriptSetManager::Observer implementation.
198   virtual void OnUserScriptsUpdated(
199       const std::set<std::string>& changed_extensions,
200       const std::vector<UserScript*>& scripts) OVERRIDE;
201
202   void UpdateActiveExtensions();
203
204   // Sets up the host permissions for |extension|.
205   void InitOriginPermissions(const Extension* extension);
206
207   // Updates the host permissions for extension to include only those in
208   // |new_patterns|, and remove from |old_patterns| that are no longer allowed.
209   void UpdateOriginPermissions(const Extension* extension,
210                                const URLPatternSet& old_patterns,
211                                const URLPatternSet& new_patterns);
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 UpdateBindings(const std::string& extension_id);
219
220   void UpdateBindingsForContext(ScriptContext* context);
221
222   void RegisterBinding(const std::string& api_name, ScriptContext* context);
223
224   void RegisterNativeHandlers(ModuleSystem* module_system,
225                               ScriptContext* context);
226
227   // Inserts static source code into |source_map_|.
228   void PopulateSourceMap();
229
230   // Returns whether the current renderer hosts a platform app.
231   bool IsWithinPlatformApp();
232
233   bool IsSandboxedPage(const GURL& url) const;
234
235   // Returns the Feature::Context type of context for a JavaScript context.
236   Feature::Context ClassifyJavaScriptContext(
237       const Extension* extension,
238       int extension_group,
239       const GURL& url,
240       const blink::WebSecurityOrigin& origin);
241
242   // Gets |field| from |object| or creates it as an empty object if it doesn't
243   // exist.
244   v8::Handle<v8::Object> GetOrCreateObject(const v8::Handle<v8::Object>& object,
245                                            const std::string& field,
246                                            v8::Isolate* isolate);
247
248   v8::Handle<v8::Object> GetOrCreateBindObjectIfAvailable(
249       const std::string& api_name,
250       std::string* bind_name,
251       ScriptContext* context);
252
253   // The delegate for this dispatcher. Not owned, but must extend beyond the
254   // Dispatcher's own lifetime.
255   DispatcherDelegate* delegate_;
256
257   // True if this renderer is running extensions.
258   bool is_extension_process_;
259
260   // Contains all loaded extensions.  This is essentially the renderer
261   // counterpart to ExtensionService in the browser. It contains information
262   // about all extensions currently loaded by the browser.
263   ExtensionSet extensions_;
264
265   // The IDs of extensions that failed to load, mapped to the error message
266   // generated on failure.
267   std::map<std::string, std::string> extension_load_errors_;
268
269   // All the bindings contexts that are currently loaded for this renderer.
270   // There is zero or one for each v8 context.
271   ScriptContextSet script_context_set_;
272
273   scoped_ptr<ContentWatcher> content_watcher_;
274
275   scoped_ptr<UserScriptSetManager> user_script_set_manager_;
276
277   scoped_ptr<ScriptInjectionManager> script_injection_manager_;
278
279   // Same as above, but on a longer timer and will run even if the process is
280   // not idle, to ensure that IdleHandle gets called eventually.
281   scoped_ptr<base::RepeatingTimer<content::RenderThread> > forced_idle_timer_;
282
283   // All declared function names.
284   std::set<std::string> function_names_;
285
286   // The extensions and apps that are active in this process.
287   std::set<std::string> active_extension_ids_;
288
289   ResourceBundleSourceMap source_map_;
290
291   // Cache for the v8 representation of extension API schemas.
292   scoped_ptr<V8SchemaRegistry> v8_schema_registry_;
293
294   // Sends API requests to the extension host.
295   scoped_ptr<RequestSender> request_sender_;
296
297   // The platforms system font family and size;
298   std::string system_font_family_;
299   std::string system_font_size_;
300
301   // Mapping of port IDs to tabs. If there is no tab, the value would be -1.
302   std::map<int, int> port_to_tab_id_map_;
303
304   // True once WebKit has been initialized (and it is therefore safe to poke).
305   bool is_webkit_initialized_;
306
307   // It is important for this to come after the ScriptInjectionManager, so that
308   // the observer is destroyed before the UserScriptSet.
309   ScopedObserver<UserScriptSetManager, UserScriptSetManager::Observer>
310       user_script_set_manager_observer_;
311
312   DISALLOW_COPY_AND_ASSIGN(Dispatcher);
313 };
314
315 }  // namespace extensions
316
317 #endif  // EXTENSIONS_RENDERER_DISPATCHER_H_