dispatcher.h 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  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. #ifndef EXTENSIONS_RENDERER_DISPATCHER_H_
  5. #define EXTENSIONS_RENDERER_DISPATCHER_H_
  6. #include <stdint.h>
  7. #include <map>
  8. #include <memory>
  9. #include <set>
  10. #include <string>
  11. #include <utility>
  12. #include <vector>
  13. #include "base/gtest_prod_util.h"
  14. #include "base/scoped_observation.h"
  15. #include "base/timer/timer.h"
  16. #include "components/version_info/version_info.h"
  17. #include "content/public/renderer/render_thread_observer.h"
  18. #include "extensions/common/event_filter.h"
  19. #include "extensions/common/extension_id.h"
  20. #include "extensions/common/extensions_client.h"
  21. #include "extensions/common/features/feature.h"
  22. #include "extensions/common/mojom/event_dispatcher.mojom.h"
  23. #include "extensions/common/mojom/feature_session_type.mojom.h"
  24. #include "extensions/common/mojom/frame.mojom.h"
  25. #include "extensions/common/mojom/host_id.mojom-forward.h"
  26. #include "extensions/common/mojom/renderer.mojom.h"
  27. #include "extensions/renderer/resource_bundle_source_map.h"
  28. #include "extensions/renderer/script_context.h"
  29. #include "extensions/renderer/script_context_set.h"
  30. #include "extensions/renderer/user_script_set_manager.h"
  31. #include "extensions/renderer/v8_schema_registry.h"
  32. #include "mojo/public/cpp/bindings/associated_receiver.h"
  33. #include "third_party/blink/public/platform/web_string.h"
  34. #include "v8/include/v8-forward.h"
  35. class ChromeRenderViewTest;
  36. class GURL;
  37. class ModuleSystem;
  38. struct ExtensionMsg_ExternalConnectionInfo;
  39. struct ExtensionMsg_TabConnectionInfo;
  40. namespace blink {
  41. class WebLocalFrame;
  42. class WebServiceWorkerContextProxy;
  43. }
  44. namespace base {
  45. class SingleThreadTaskRunner;
  46. }
  47. namespace content {
  48. class RenderThread;
  49. } // namespace content
  50. namespace extensions {
  51. // Constant to define the default profile id for the renderer to 0.
  52. // Since each renderer is associated with a single context, we don't need
  53. // separate ids for the profile.
  54. const int kRendererProfileId = 0;
  55. class ContentWatcher;
  56. class DispatcherDelegate;
  57. class Extension;
  58. class NativeExtensionBindingsSystem;
  59. class IPCMessageSender;
  60. class ScriptContext;
  61. class ScriptContextSetIterable;
  62. class ScriptInjectionManager;
  63. class WorkerScriptContextSet;
  64. struct Message;
  65. struct PortId;
  66. // Dispatches extension control messages sent to the renderer and stores
  67. // renderer extension related state.
  68. class Dispatcher : public content::RenderThreadObserver,
  69. public UserScriptSetManager::Observer,
  70. public mojom::Renderer,
  71. public mojom::EventDispatcher {
  72. public:
  73. explicit Dispatcher(std::unique_ptr<DispatcherDelegate> delegate);
  74. Dispatcher(const Dispatcher&) = delete;
  75. Dispatcher& operator=(const Dispatcher&) = delete;
  76. ~Dispatcher() override;
  77. // Returns Service Worker ScriptContexts belonging to current worker thread.
  78. static WorkerScriptContextSet* GetWorkerScriptContextSet();
  79. const ScriptContextSet& script_context_set() const {
  80. return *script_context_set_;
  81. }
  82. // Returns iterator to iterate over all main thread ScriptContexts.
  83. ScriptContextSetIterable* script_context_set_iterator() {
  84. return script_context_set_.get();
  85. }
  86. V8SchemaRegistry* v8_schema_registry() { return v8_schema_registry_.get(); }
  87. const std::string& webview_partition_id() { return webview_partition_id_; }
  88. bool activity_logging_enabled() const { return activity_logging_enabled_; }
  89. void OnRenderThreadStarted(content::RenderThread* render_thread);
  90. void OnRenderFrameCreated(content::RenderFrame* render_frame);
  91. bool IsExtensionActive(const std::string& extension_id) const;
  92. void DidCreateScriptContext(blink::WebLocalFrame* frame,
  93. const v8::Local<v8::Context>& context,
  94. int32_t world_id);
  95. // This is called when a service worker is ready to evaluate the toplevel
  96. // script. This method suspends the service worker if:
  97. // * the service worker is background of a service worker based extension,
  98. // and
  99. // * the extension isn't loaded yet.
  100. // Suspending background service worker is required because we need to
  101. // install extension API bindings before executing the service worker.
  102. // TODO(crbug.com/1000890): Figure out better way to coalesce them.
  103. //
  104. // Runs on the service worker thread and should only use thread-safe member
  105. // variables.
  106. void DidInitializeServiceWorkerContextOnWorkerThread(
  107. blink::WebServiceWorkerContextProxy* context_proxy,
  108. const GURL& service_worker_scope,
  109. const GURL& script_url);
  110. // This is called immediately before a service worker evaluates the
  111. // toplevel script. This method installs extension API bindings.
  112. //
  113. // Runs on a different thread and should only use thread-safe member
  114. // variables.
  115. void WillEvaluateServiceWorkerOnWorkerThread(
  116. blink::WebServiceWorkerContextProxy* context_proxy,
  117. v8::Local<v8::Context> v8_context,
  118. int64_t service_worker_version_id,
  119. const GURL& service_worker_scope,
  120. const GURL& script_url);
  121. void WillReleaseScriptContext(blink::WebLocalFrame* frame,
  122. const v8::Local<v8::Context>& context,
  123. int32_t world_id);
  124. // Runs on worker thread and should not use any member variables.
  125. void DidStartServiceWorkerContextOnWorkerThread(
  126. int64_t service_worker_version_id,
  127. const GURL& service_worker_scope,
  128. const GURL& script_url);
  129. // Runs on a different thread and should not use any member variables.
  130. void WillDestroyServiceWorkerContextOnWorkerThread(
  131. v8::Local<v8::Context> v8_context,
  132. int64_t service_worker_version_id,
  133. const GURL& service_worker_scope,
  134. const GURL& script_url);
  135. // This method is not allowed to run JavaScript code in the frame.
  136. void DidCreateDocumentElement(blink::WebLocalFrame* frame);
  137. // These methods may run (untrusted) JavaScript code in the frame, and
  138. // cause |render_frame| to become invalid.
  139. void RunScriptsAtDocumentStart(content::RenderFrame* render_frame);
  140. void RunScriptsAtDocumentEnd(content::RenderFrame* render_frame);
  141. void RunScriptsAtDocumentIdle(content::RenderFrame* render_frame);
  142. // Dispatches the event named |event_name| to all render views.
  143. void DispatchEventHelper(const std::string& extension_id,
  144. const std::string& event_name,
  145. const base::Value::List& event_args,
  146. mojom::EventFilteringInfoPtr filtering_info) const;
  147. // Shared implementation of the various MessageInvoke IPCs.
  148. void InvokeModuleSystemMethod(content::RenderFrame* render_frame,
  149. const std::string& extension_id,
  150. const std::string& module_name,
  151. const std::string& function_name,
  152. const base::Value::List& args);
  153. void ExecuteDeclarativeScript(content::RenderFrame* render_frame,
  154. int tab_id,
  155. const ExtensionId& extension_id,
  156. const std::string& script_id,
  157. const GURL& url);
  158. // Executes the code described in |param| and calls |callback| if it's done.
  159. void ExecuteCode(mojom::ExecuteCodeParamsPtr param,
  160. mojom::LocalFrame::ExecuteCodeCallback callback,
  161. content::RenderFrame* render_frame);
  162. struct JsResourceInfo {
  163. const char* name = nullptr;
  164. int id = 0;
  165. };
  166. // Returns a list of resources for the JS modules to add to the source map.
  167. static std::vector<JsResourceInfo> GetJsResources();
  168. static void RegisterNativeHandlers(
  169. ModuleSystem* module_system,
  170. ScriptContext* context,
  171. Dispatcher* dispatcher,
  172. NativeExtensionBindingsSystem* bindings_system,
  173. V8SchemaRegistry* v8_schema_registry);
  174. NativeExtensionBindingsSystem* bindings_system() {
  175. return bindings_system_.get();
  176. }
  177. private:
  178. // The RendererPermissionsPolicyDelegateTest.CannotScriptWebstore test needs
  179. // to call the ActivateExtension IPCs.
  180. friend class ::ChromeRenderViewTest;
  181. FRIEND_TEST_ALL_PREFIXES(RendererPermissionsPolicyDelegateTest,
  182. CannotScriptWebstore);
  183. // RenderThreadObserver implementation:
  184. bool OnControlMessageReceived(const IPC::Message& message) override;
  185. void RegisterMojoInterfaces(
  186. blink::AssociatedInterfaceRegistry* associated_interfaces) override;
  187. void UnregisterMojoInterfaces(
  188. blink::AssociatedInterfaceRegistry* associated_interfaces) override;
  189. // mojom::Renderer implementation:
  190. void ActivateExtension(const std::string& extension_id) override;
  191. void SetActivityLoggingEnabled(bool enabled) override;
  192. void LoadExtensions(
  193. std::vector<mojom::ExtensionLoadedParamsPtr> loaded_extensions) override;
  194. void UnloadExtension(const std::string& extension_id) override;
  195. void SuspendExtension(
  196. const std::string& extension_id,
  197. mojom::Renderer::SuspendExtensionCallback callback) override;
  198. void CancelSuspendExtension(const std::string& extension_id) override;
  199. void SetDeveloperMode(bool current_developer_mode) override;
  200. void SetSessionInfo(version_info::Channel channel,
  201. mojom::FeatureSessionType session_type,
  202. bool lock_screen_context) override;
  203. void SetSystemFont(const std::string& font_family,
  204. const std::string& font_size) override;
  205. void SetWebViewPartitionID(const std::string& partition_id) override;
  206. void SetScriptingAllowlist(
  207. const std::vector<std::string>& extension_ids) override;
  208. void ShouldSuspend(ShouldSuspendCallback callback) override;
  209. void TransferBlobs(TransferBlobsCallback callback) override;
  210. void UpdatePermissions(const std::string& extension_id,
  211. PermissionSet active_permissions,
  212. PermissionSet withheld_permissions,
  213. URLPatternSet policy_blocked_hosts,
  214. URLPatternSet policy_allowed_hosts,
  215. bool uses_default_policy_host_restrictions) override;
  216. void UpdateDefaultPolicyHostRestrictions(
  217. URLPatternSet default_policy_blocked_hosts,
  218. URLPatternSet default_policy_allowed_hosts) override;
  219. void UpdateUserHostRestrictions(URLPatternSet user_blocked_hosts,
  220. URLPatternSet user_allowed_hosts) override;
  221. void UpdateTabSpecificPermissions(const std::string& extension_id,
  222. URLPatternSet new_hosts,
  223. int tab_id,
  224. bool update_origin_allowlist) override;
  225. void UpdateUserScripts(base::ReadOnlySharedMemoryRegion shared_memory,
  226. mojom::HostIDPtr host_id) override;
  227. void ClearTabSpecificPermissions(
  228. const std::vector<std::string>& extension_ids,
  229. int tab_id,
  230. bool update_origin_allowlist) override;
  231. void WatchPages(const std::vector<std::string>& css_selectors) override;
  232. void OnRendererAssociatedRequest(
  233. mojo::PendingAssociatedReceiver<mojom::Renderer> receiver);
  234. void OnEventDispatcherRequest(
  235. mojo::PendingAssociatedReceiver<mojom::EventDispatcher> receiver);
  236. void OnDeliverMessage(int worker_thread_id,
  237. const PortId& target_port_id,
  238. const Message& message);
  239. void OnDispatchOnConnect(int worker_thread_id,
  240. const PortId& target_port_id,
  241. const std::string& channel_name,
  242. const ExtensionMsg_TabConnectionInfo& source,
  243. const ExtensionMsg_ExternalConnectionInfo& info);
  244. void OnDispatchOnDisconnect(int worker_thread_id,
  245. const PortId& port_id,
  246. const std::string& error_message);
  247. // mojom::EventDispatcher implementation.
  248. void DispatchEvent(mojom::DispatchEventParamsPtr params,
  249. base::Value::List event_args) override;
  250. // UserScriptSetManager::Observer implementation.
  251. void OnUserScriptsUpdated(const mojom::HostID& changed_host) override;
  252. void UpdateActiveExtensions();
  253. // Sets up the host permissions for |extension|.
  254. void InitOriginPermissions(const Extension* extension);
  255. // Updates the host permissions for the extension url to include only those
  256. // the extension currently has, removing any old entries.
  257. void UpdateOriginPermissions(const Extension& extension);
  258. // Enable custom element allowlist in Apps.
  259. void EnableCustomElementAllowlist();
  260. // Adds or removes bindings for all contexts.
  261. void UpdateAllBindings();
  262. // Adds or removes bindings for every context belonging to |extension|, due to
  263. // permissions change in the extension.
  264. void UpdateBindingsForExtension(const Extension& extension);
  265. void RegisterNativeHandlers(ModuleSystem* module_system,
  266. ScriptContext* context,
  267. NativeExtensionBindingsSystem* bindings_system,
  268. V8SchemaRegistry* v8_schema_registry);
  269. // Inserts static source code into |source_map_|.
  270. void PopulateSourceMap();
  271. // Returns whether the current renderer hosts a platform app.
  272. bool IsWithinPlatformApp();
  273. // Requires the GuestView modules in the module system of the ScriptContext
  274. // |context|.
  275. void RequireGuestViewModules(ScriptContext* context);
  276. // Creates the NativeExtensionBindingsSystem. Note: this may be called on any
  277. // thread, and thus cannot mutate any state or rely on state which can be
  278. // mutated in Dispatcher.
  279. std::unique_ptr<NativeExtensionBindingsSystem> CreateBindingsSystem(
  280. std::unique_ptr<IPCMessageSender> ipc_sender);
  281. void ResumeEvaluationOnWorkerThread(const ExtensionId& extension_id);
  282. // The delegate for this dispatcher to handle embedder-specific logic.
  283. std::unique_ptr<DispatcherDelegate> delegate_;
  284. // The IDs of extensions that failed to load, mapped to the error message
  285. // generated on failure.
  286. std::map<std::string, std::string> extension_load_errors_;
  287. // All the bindings contexts that are currently loaded for this renderer.
  288. // There is zero or one for each v8 context.
  289. std::unique_ptr<ScriptContextSet> script_context_set_;
  290. std::unique_ptr<ContentWatcher> content_watcher_;
  291. std::unique_ptr<UserScriptSetManager> user_script_set_manager_;
  292. std::unique_ptr<ScriptInjectionManager> script_injection_manager_;
  293. // The extensions and apps that are active in this process.
  294. ExtensionIdSet active_extension_ids_;
  295. ResourceBundleSourceMap source_map_;
  296. // Cache for the v8 representation of extension API schemas.
  297. std::unique_ptr<V8SchemaRegistry> v8_schema_registry_;
  298. // The bindings system associated with the main thread.
  299. std::unique_ptr<NativeExtensionBindingsSystem> bindings_system_;
  300. // The platforms system font family and size;
  301. std::string system_font_family_;
  302. std::string system_font_size_;
  303. // It is important for this to come after the ScriptInjectionManager, so that
  304. // the observer is destroyed before the UserScriptSet.
  305. base::ScopedObservation<UserScriptSetManager, UserScriptSetManager::Observer>
  306. user_script_set_manager_observation_{this};
  307. // Whether or not extension activity is enabled.
  308. bool activity_logging_enabled_;
  309. // The WebView partition ID associated with this process's storage partition,
  310. // if this renderer is a WebView guest render process. Otherwise, this will be
  311. // empty.
  312. std::string webview_partition_id_;
  313. // Extensions renderer receiver. This is an associated receiver because
  314. // it is dependent on other messages sent on other associated channels.
  315. mojo::AssociatedReceiver<mojom::Renderer> receiver_;
  316. // Extensions mojom::EventDispatcher receiver. This is an associated receiver
  317. // because it is dependent on other messages sent on other associated
  318. // channels.
  319. mojo::AssociatedReceiver<mojom::EventDispatcher> dispatcher_;
  320. // Used to hold a service worker information which is ready to execute but the
  321. // onloaded message haven't been received yet. We need to defer service worker
  322. // execution until the ExtensionMsg_Loaded message is received because we can
  323. // install extension bindings only after the onload message is received.
  324. // TODO(bashi): Consider to have a separate class to put this logic?
  325. struct PendingServiceWorker {
  326. scoped_refptr<base::SingleThreadTaskRunner> task_runner;
  327. blink::WebServiceWorkerContextProxy* context_proxy;
  328. PendingServiceWorker(blink::WebServiceWorkerContextProxy* context_proxy);
  329. ~PendingServiceWorker();
  330. };
  331. // This will be accessed both from the main thread and worker threads.
  332. std::map<ExtensionId, std::unique_ptr<PendingServiceWorker>>
  333. service_workers_paused_for_on_loaded_message_;
  334. base::Lock service_workers_paused_for_on_loaded_message_lock_;
  335. };
  336. } // namespace extensions
  337. #endif // EXTENSIONS_RENDERER_DISPATCHER_H_