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.
5 #ifndef CHROME_BROWSER_EXTENSIONS_API_MESSAGING_MESSAGE_SERVICE_H_
6 #define CHROME_BROWSER_EXTENSIONS_API_MESSAGING_MESSAGE_SERVICE_H_
13 #include "base/compiler_specific.h"
14 #include "base/memory/scoped_ptr.h"
15 #include "base/memory/weak_ptr.h"
16 #include "base/values.h"
17 #include "chrome/browser/extensions/api/messaging/message_property_provider.h"
18 #include "content/public/browser/notification_observer.h"
19 #include "content/public/browser/notification_registrar.h"
20 #include "extensions/browser/api/messaging/native_message_host.h"
21 #include "extensions/browser/browser_context_keyed_api_factory.h"
22 #include "extensions/common/api/messaging/message.h"
29 class RenderProcessHost
;
33 namespace extensions
{
36 class LazyBackgroundTaskQueue
;
38 // This class manages message and event passing between renderer processes.
39 // It maintains a list of processes that are listening to events and a set of
42 // Messaging works this way:
43 // - An extension-owned script context (like a background page or a content
44 // script) adds an event listener to the "onConnect" event.
45 // - Another context calls "runtime.connect()" to open a channel to the
46 // extension process, or an extension context calls "tabs.connect(tabId)" to
47 // open a channel to the content scripts for the given tab. The EMS notifies
48 // the target process/tab, which then calls the onConnect event in every
49 // context owned by the connecting extension in that process/tab.
50 // - Once the channel is established, either side can call postMessage to send
51 // a message to the opposite side of the channel, which may have multiple
55 // channel: connection between two ports
56 // port: an IPC::Message::Process interface and an optional routing_id (in the
57 // case that the port is a tab). The Process is usually either a
58 // RenderProcessHost or a RenderViewHost.
59 class MessageService
: public BrowserContextKeyedAPI
,
60 public content::NotificationObserver
{
62 // A messaging channel. Note that the opening port can be the same as the
63 // receiver, if an extension background page wants to talk to its tab (for
65 struct MessageChannel
;
67 // One side of the communication handled by extensions::MessageService.
70 virtual ~MessagePort() {}
71 // Notify the port that the channel has been opened.
72 virtual void DispatchOnConnect(int dest_port_id
,
73 const std::string
& channel_name
,
74 scoped_ptr
<base::DictionaryValue
> source_tab
,
78 int guest_render_frame_routing_id
,
79 const std::string
& source_extension_id
,
80 const std::string
& target_extension_id
,
81 const GURL
& source_url
,
82 const std::string
& tls_channel_id
) {}
84 // Notify the port that the channel has been closed. If |error_message| is
85 // non-empty, it indicates an error occurred while opening the connection.
86 virtual void DispatchOnDisconnect(int source_port_id
,
87 const std::string
& error_message
) {}
89 // Dispatch a message to this end of the communication.
90 virtual void DispatchOnMessage(const Message
& message
,
91 int target_port_id
) = 0;
93 // MessagPorts that target extensions will need to adjust their keepalive
94 // counts for their lazy background page.
95 virtual void IncrementLazyKeepaliveCount() {}
96 virtual void DecrementLazyKeepaliveCount() {}
98 // Get the RenderProcessHost (if any) associated with the port.
99 virtual content::RenderProcessHost
* GetRenderProcessHost();
105 DISALLOW_COPY_AND_ASSIGN(MessagePort
);
108 enum PolicyPermission
{
109 DISALLOW
, // The host is not allowed.
110 ALLOW_SYSTEM_ONLY
, // Allowed only when installed on system level.
111 ALLOW_ALL
, // Allowed when installed on system or user level.
114 static PolicyPermission
IsNativeMessagingHostAllowed(
115 const PrefService
* pref_service
,
116 const std::string
& native_host_name
);
118 // Allocates a pair of port ids.
119 // NOTE: this can be called from any thread.
120 static void AllocatePortIdPair(int* port1
, int* port2
);
122 explicit MessageService(content::BrowserContext
* context
);
123 ~MessageService() override
;
125 // BrowserContextKeyedAPI implementation.
126 static BrowserContextKeyedAPIFactory
<MessageService
>* GetFactoryInstance();
128 // Convenience method to get the MessageService for a browser context.
129 static MessageService
* Get(content::BrowserContext
* context
);
131 // Given an extension's ID, opens a channel between the given renderer "port"
132 // and every listening context owned by that extension. |channel_name| is
133 // an optional identifier for use by extension developers.
134 void OpenChannelToExtension(
135 int source_process_id
, int source_routing_id
, int receiver_port_id
,
136 const std::string
& source_extension_id
,
137 const std::string
& target_extension_id
,
138 const GURL
& source_url
,
139 const std::string
& channel_name
,
140 bool include_tls_channel_id
);
142 // Same as above, but opens a channel to the tab with the given ID. Messages
143 // are restricted to that tab, so if there are multiple tabs in that process,
144 // only the targeted tab will receive messages.
145 void OpenChannelToTab(int source_process_id
,
146 int receiver_port_id
,
149 const std::string
& extension_id
,
150 const std::string
& channel_name
);
152 void OpenChannelToNativeApp(
153 int source_process_id
,
154 int source_routing_id
,
155 int receiver_port_id
,
156 const std::string
& source_extension_id
,
157 const std::string
& native_app_name
);
159 // Closes the message channel associated with the given port, and notifies
161 void CloseChannel(int port_id
, const std::string
& error_message
);
163 // Enqueues a message on a pending channel, or sends a message to the given
164 // port if the channel isn't pending.
165 void PostMessage(int port_id
, const Message
& message
);
168 friend class MockMessageService
;
169 friend class BrowserContextKeyedAPIFactory
<MessageService
>;
170 struct OpenChannelParams
;
172 // A map of channel ID to its channel object.
173 typedef std::map
<int, MessageChannel
*> MessageChannelMap
;
175 typedef std::pair
<int, Message
> PendingMessage
;
176 typedef std::vector
<PendingMessage
> PendingMessagesQueue
;
177 // A set of channel IDs waiting to complete opening, and any pending messages
178 // queued to be sent on those channels.
179 typedef std::map
<int, PendingMessagesQueue
> PendingChannelMap
;
181 // A map of channel ID to information about the extension that is waiting
182 // for that channel to open. Used for lazy background pages.
183 typedef std::string ExtensionID
;
184 typedef std::pair
<content::BrowserContext
*, ExtensionID
>
185 PendingLazyBackgroundPageChannel
;
186 typedef std::map
<int, PendingLazyBackgroundPageChannel
>
187 PendingLazyBackgroundPageChannelMap
;
189 // Common among OpenChannel* variants.
190 void OpenChannelImpl(scoped_ptr
<OpenChannelParams
> params
);
192 void CloseChannelImpl(MessageChannelMap::iterator channel_iter
,
194 const std::string
& error_message
,
195 bool notify_other_port
);
197 // Have MessageService take ownership of |channel|, and remove any pending
198 // channels with the same id.
199 void AddChannel(MessageChannel
* channel
, int receiver_port_id
);
201 // content::NotificationObserver interface.
202 void Observe(int type
,
203 const content::NotificationSource
& source
,
204 const content::NotificationDetails
& details
) override
;
206 // A process that might be in our list of channels has closed.
207 void OnProcessClosed(content::RenderProcessHost
* process
);
209 // If the channel is being opened from an incognito tab the user must allow
211 void OnOpenChannelAllowed(scoped_ptr
<OpenChannelParams
> params
, bool allowed
);
212 void GotChannelID(scoped_ptr
<OpenChannelParams
> params
,
213 const std::string
& tls_channel_id
);
215 // Enqueues a message on a pending channel.
216 void EnqueuePendingMessage(int port_id
, int channel_id
,
217 const Message
& message
);
219 // Enqueues a message on a channel pending on a lazy background page load.
220 void EnqueuePendingMessageForLazyBackgroundLoad(int port_id
,
222 const Message
& message
);
224 // Immediately sends a message to the given port.
225 void DispatchMessage(int port_id
, MessageChannel
* channel
,
226 const Message
& message
);
228 // Potentially registers a pending task with the LazyBackgroundTaskQueue
229 // to open a channel. Returns true if a task was queued.
230 // Takes ownership of |params| if true is returned.
231 bool MaybeAddPendingLazyBackgroundPageOpenChannelTask(
232 content::BrowserContext
* context
,
233 const Extension
* extension
,
234 scoped_ptr
<OpenChannelParams
>* params
,
235 const PendingMessagesQueue
& pending_messages
);
237 // Callbacks for LazyBackgroundTaskQueue tasks. The queue passes in an
238 // ExtensionHost to its task callbacks, though some of our callbacks don't
239 // use that argument.
240 void PendingLazyBackgroundPageOpenChannel(
241 scoped_ptr
<OpenChannelParams
> params
,
242 int source_process_id
,
243 extensions::ExtensionHost
* host
);
244 void PendingLazyBackgroundPageCloseChannel(int port_id
,
245 const std::string
& error_message
,
246 extensions::ExtensionHost
* host
) {
248 CloseChannel(port_id
, error_message
);
250 void PendingLazyBackgroundPagePostMessage(int port_id
,
251 const Message
& message
,
252 extensions::ExtensionHost
* host
) {
254 PostMessage(port_id
, message
);
257 // Immediate dispatches a disconnect to |source| for |port_id|. Sets source's
258 // runtime.lastMessage to |error_message|, if any.
259 void DispatchOnDisconnect(content::RenderProcessHost
* source
,
261 const std::string
& error_message
);
263 void DispatchPendingMessages(const PendingMessagesQueue
& queue
,
266 // BrowserContextKeyedAPI implementation.
267 static const char* service_name() {
268 return "MessageService";
270 static const bool kServiceRedirectedInIncognito
= true;
271 static const bool kServiceIsCreatedWithBrowserContext
= false;
272 static const bool kServiceIsNULLWhileTesting
= true;
274 content::NotificationRegistrar registrar_
;
275 MessageChannelMap channels_
;
276 // A set of channel IDs waiting for TLS channel IDs to complete opening, and
277 // any pending messages queued to be sent on those channels. This and the
278 // following two maps form a pipeline where messages are queued before the
279 // channel they are addressed to is ready.
280 PendingChannelMap pending_tls_channel_id_channels_
;
281 // A set of channel IDs waiting for user permission to cross the border
282 // between an incognito page and an app or extension, and any pending messages
283 // queued to be sent on those channels.
284 PendingChannelMap pending_incognito_channels_
;
285 PendingLazyBackgroundPageChannelMap pending_lazy_background_page_channels_
;
286 MessagePropertyProvider property_provider_
;
288 // Weak pointer. Guaranteed to outlive this class.
289 LazyBackgroundTaskQueue
* lazy_background_task_queue_
;
291 base::WeakPtrFactory
<MessageService
> weak_factory_
;
293 DISALLOW_COPY_AND_ASSIGN(MessageService
);
296 } // namespace extensions
298 #endif // CHROME_BROWSER_EXTENSIONS_API_MESSAGING_MESSAGE_SERVICE_H_