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 implementation for opening a channel configured by |params|.
191 // |target_extension| will be non-null if |params->target_extension_id| is
192 // non-empty, that is, if the target is an extension, it must exist.
194 // |did_enqueue| will be true if the channel opening was delayed while
195 // waiting for an event page to start, false otherwise.
196 void OpenChannelImpl(content::BrowserContext
* browser_context
,
197 scoped_ptr
<OpenChannelParams
> params
,
198 const Extension
* target_extension
,
201 void CloseChannelImpl(MessageChannelMap::iterator channel_iter
,
203 const std::string
& error_message
,
204 bool notify_other_port
);
206 // Have MessageService take ownership of |channel|, and remove any pending
207 // channels with the same id.
208 void AddChannel(MessageChannel
* channel
, int receiver_port_id
);
210 // content::NotificationObserver interface.
211 void Observe(int type
,
212 const content::NotificationSource
& source
,
213 const content::NotificationDetails
& details
) override
;
215 // A process that might be in our list of channels has closed.
216 void OnProcessClosed(content::RenderProcessHost
* process
);
218 // If the channel is being opened from an incognito tab the user must allow
220 void OnOpenChannelAllowed(scoped_ptr
<OpenChannelParams
> params
, bool allowed
);
221 void GotChannelID(scoped_ptr
<OpenChannelParams
> params
,
222 const std::string
& tls_channel_id
);
224 // Enqueues a message on a pending channel.
225 void EnqueuePendingMessage(int port_id
, int channel_id
,
226 const Message
& message
);
228 // Enqueues a message on a channel pending on a lazy background page load.
229 void EnqueuePendingMessageForLazyBackgroundLoad(int port_id
,
231 const Message
& message
);
233 // Immediately sends a message to the given port.
234 void DispatchMessage(int port_id
, MessageChannel
* channel
,
235 const Message
& message
);
237 // Potentially registers a pending task with the LazyBackgroundTaskQueue
238 // to open a channel. Returns true if a task was queued.
239 // Takes ownership of |params| if true is returned.
240 bool MaybeAddPendingLazyBackgroundPageOpenChannelTask(
241 content::BrowserContext
* context
,
242 const Extension
* extension
,
243 scoped_ptr
<OpenChannelParams
>* params
,
244 const PendingMessagesQueue
& pending_messages
);
246 // Callbacks for LazyBackgroundTaskQueue tasks. The queue passes in an
247 // ExtensionHost to its task callbacks, though some of our callbacks don't
248 // use that argument.
249 void PendingLazyBackgroundPageOpenChannel(
250 scoped_ptr
<OpenChannelParams
> params
,
251 int source_process_id
,
252 extensions::ExtensionHost
* host
);
253 void PendingLazyBackgroundPageCloseChannel(int port_id
,
254 const std::string
& error_message
,
255 extensions::ExtensionHost
* host
) {
257 CloseChannel(port_id
, error_message
);
259 void PendingLazyBackgroundPagePostMessage(int port_id
,
260 const Message
& message
,
261 extensions::ExtensionHost
* host
) {
263 PostMessage(port_id
, message
);
266 // Immediate dispatches a disconnect to |source| for |port_id|. Sets source's
267 // runtime.lastMessage to |error_message|, if any.
268 void DispatchOnDisconnect(content::RenderProcessHost
* source
,
270 const std::string
& error_message
);
272 void DispatchPendingMessages(const PendingMessagesQueue
& queue
,
275 // BrowserContextKeyedAPI implementation.
276 static const char* service_name() {
277 return "MessageService";
279 static const bool kServiceRedirectedInIncognito
= true;
280 static const bool kServiceIsCreatedWithBrowserContext
= false;
281 static const bool kServiceIsNULLWhileTesting
= true;
283 content::NotificationRegistrar registrar_
;
284 MessageChannelMap channels_
;
285 // A set of channel IDs waiting for TLS channel IDs to complete opening, and
286 // any pending messages queued to be sent on those channels. This and the
287 // following two maps form a pipeline where messages are queued before the
288 // channel they are addressed to is ready.
289 PendingChannelMap pending_tls_channel_id_channels_
;
290 // A set of channel IDs waiting for user permission to cross the border
291 // between an incognito page and an app or extension, and any pending messages
292 // queued to be sent on those channels.
293 PendingChannelMap pending_incognito_channels_
;
294 PendingLazyBackgroundPageChannelMap pending_lazy_background_page_channels_
;
295 MessagePropertyProvider property_provider_
;
297 // Weak pointer. Guaranteed to outlive this class.
298 LazyBackgroundTaskQueue
* lazy_background_task_queue_
;
300 base::WeakPtrFactory
<MessageService
> weak_factory_
;
302 DISALLOW_COPY_AND_ASSIGN(MessageService
);
305 } // namespace extensions
307 #endif // CHROME_BROWSER_EXTENSIONS_API_MESSAGING_MESSAGE_SERVICE_H_