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
,
79 int guest_render_frame_routing_id
,
80 const std::string
& source_extension_id
,
81 const std::string
& target_extension_id
,
82 const GURL
& source_url
,
83 const std::string
& tls_channel_id
) {}
85 // Notify the port that the channel has been closed. If |error_message| is
86 // non-empty, it indicates an error occurred while opening the connection.
87 virtual void DispatchOnDisconnect(int source_port_id
,
88 const std::string
& error_message
) {}
90 // Dispatch a message to this end of the communication.
91 virtual void DispatchOnMessage(const Message
& message
,
92 int target_port_id
) = 0;
94 // MessagPorts that target extensions will need to adjust their keepalive
95 // counts for their lazy background page.
96 virtual void IncrementLazyKeepaliveCount() {}
97 virtual void DecrementLazyKeepaliveCount() {}
99 // Get the RenderProcessHost (if any) associated with the port.
100 virtual content::RenderProcessHost
* GetRenderProcessHost();
106 DISALLOW_COPY_AND_ASSIGN(MessagePort
);
109 enum PolicyPermission
{
110 DISALLOW
, // The host is not allowed.
111 ALLOW_SYSTEM_ONLY
, // Allowed only when installed on system level.
112 ALLOW_ALL
, // Allowed when installed on system or user level.
115 static PolicyPermission
IsNativeMessagingHostAllowed(
116 const PrefService
* pref_service
,
117 const std::string
& native_host_name
);
119 // Allocates a pair of port ids.
120 // NOTE: this can be called from any thread.
121 static void AllocatePortIdPair(int* port1
, int* port2
);
123 explicit MessageService(content::BrowserContext
* context
);
124 ~MessageService() override
;
126 // BrowserContextKeyedAPI implementation.
127 static BrowserContextKeyedAPIFactory
<MessageService
>* GetFactoryInstance();
129 // Convenience method to get the MessageService for a browser context.
130 static MessageService
* Get(content::BrowserContext
* context
);
132 // Given an extension's ID, opens a channel between the given renderer "port"
133 // and every listening context owned by that extension. |channel_name| is
134 // an optional identifier for use by extension developers.
135 void OpenChannelToExtension(
136 int source_process_id
, int source_routing_id
, int receiver_port_id
,
137 const std::string
& source_extension_id
,
138 const std::string
& target_extension_id
,
139 const GURL
& source_url
,
140 const std::string
& channel_name
,
141 bool include_tls_channel_id
);
143 // Same as above, but opens a channel to the tab with the given ID. Messages
144 // are restricted to that tab, so if there are multiple tabs in that process,
145 // only the targeted tab will receive messages.
146 void OpenChannelToTab(int source_process_id
,
147 int receiver_port_id
,
150 const std::string
& extension_id
,
151 const std::string
& channel_name
);
153 void OpenChannelToNativeApp(
154 int source_process_id
,
155 int source_routing_id
,
156 int receiver_port_id
,
157 const std::string
& source_extension_id
,
158 const std::string
& native_app_name
);
160 // Closes the message channel associated with the given port, and notifies
162 void CloseChannel(int port_id
, const std::string
& error_message
);
164 // Enqueues a message on a pending channel, or sends a message to the given
165 // port if the channel isn't pending.
166 void PostMessage(int port_id
, const Message
& message
);
169 friend class MockMessageService
;
170 friend class BrowserContextKeyedAPIFactory
<MessageService
>;
171 struct OpenChannelParams
;
173 // A map of channel ID to its channel object.
174 typedef std::map
<int, MessageChannel
*> MessageChannelMap
;
176 typedef std::pair
<int, Message
> PendingMessage
;
177 typedef std::vector
<PendingMessage
> PendingMessagesQueue
;
178 // A set of channel IDs waiting to complete opening, and any pending messages
179 // queued to be sent on those channels.
180 typedef std::map
<int, PendingMessagesQueue
> PendingChannelMap
;
182 // A map of channel ID to information about the extension that is waiting
183 // for that channel to open. Used for lazy background pages.
184 typedef std::string ExtensionID
;
185 typedef std::pair
<content::BrowserContext
*, ExtensionID
>
186 PendingLazyBackgroundPageChannel
;
187 typedef std::map
<int, PendingLazyBackgroundPageChannel
>
188 PendingLazyBackgroundPageChannelMap
;
190 // Common implementation for opening a channel configured by |params|.
192 // |target_extension| will be non-null if |params->target_extension_id| is
193 // non-empty, that is, if the target is an extension, it must exist.
195 // |did_enqueue| will be true if the channel opening was delayed while
196 // waiting for an event page to start, false otherwise.
197 void OpenChannelImpl(content::BrowserContext
* browser_context
,
198 scoped_ptr
<OpenChannelParams
> params
,
199 const Extension
* target_extension
,
202 void CloseChannelImpl(MessageChannelMap::iterator channel_iter
,
204 const std::string
& error_message
,
205 bool notify_other_port
);
207 // Have MessageService take ownership of |channel|, and remove any pending
208 // channels with the same id.
209 void AddChannel(MessageChannel
* channel
, int receiver_port_id
);
211 // content::NotificationObserver interface.
212 void Observe(int type
,
213 const content::NotificationSource
& source
,
214 const content::NotificationDetails
& details
) override
;
216 // A process that might be in our list of channels has closed.
217 void OnProcessClosed(content::RenderProcessHost
* process
);
219 // If the channel is being opened from an incognito tab the user must allow
221 void OnOpenChannelAllowed(scoped_ptr
<OpenChannelParams
> params
, bool allowed
);
222 void GotChannelID(scoped_ptr
<OpenChannelParams
> params
,
223 const std::string
& tls_channel_id
);
225 // Enqueues a message on a pending channel.
226 void EnqueuePendingMessage(int port_id
, int channel_id
,
227 const Message
& message
);
229 // Enqueues a message on a channel pending on a lazy background page load.
230 void EnqueuePendingMessageForLazyBackgroundLoad(int port_id
,
232 const Message
& message
);
234 // Immediately sends a message to the given port.
235 void DispatchMessage(int port_id
, MessageChannel
* channel
,
236 const Message
& message
);
238 // Potentially registers a pending task with the LazyBackgroundTaskQueue
239 // to open a channel. Returns true if a task was queued.
240 // Takes ownership of |params| if true is returned.
241 bool MaybeAddPendingLazyBackgroundPageOpenChannelTask(
242 content::BrowserContext
* context
,
243 const Extension
* extension
,
244 scoped_ptr
<OpenChannelParams
>* params
,
245 const PendingMessagesQueue
& pending_messages
);
247 // Callbacks for LazyBackgroundTaskQueue tasks. The queue passes in an
248 // ExtensionHost to its task callbacks, though some of our callbacks don't
249 // use that argument.
250 void PendingLazyBackgroundPageOpenChannel(
251 scoped_ptr
<OpenChannelParams
> params
,
252 int source_process_id
,
253 extensions::ExtensionHost
* host
);
254 void PendingLazyBackgroundPageCloseChannel(int port_id
,
255 const std::string
& error_message
,
256 extensions::ExtensionHost
* host
) {
258 CloseChannel(port_id
, error_message
);
260 void PendingLazyBackgroundPagePostMessage(int port_id
,
261 const Message
& message
,
262 extensions::ExtensionHost
* host
) {
264 PostMessage(port_id
, message
);
267 // Immediate dispatches a disconnect to |source| for |port_id|. Sets source's
268 // runtime.lastMessage to |error_message|, if any.
269 void DispatchOnDisconnect(content::RenderProcessHost
* source
,
271 const std::string
& error_message
);
273 void DispatchPendingMessages(const PendingMessagesQueue
& queue
,
276 // BrowserContextKeyedAPI implementation.
277 static const char* service_name() {
278 return "MessageService";
280 static const bool kServiceRedirectedInIncognito
= true;
281 static const bool kServiceIsCreatedWithBrowserContext
= false;
282 static const bool kServiceIsNULLWhileTesting
= true;
284 content::NotificationRegistrar registrar_
;
285 MessageChannelMap channels_
;
286 // A set of channel IDs waiting for TLS channel IDs to complete opening, and
287 // any pending messages queued to be sent on those channels. This and the
288 // following two maps form a pipeline where messages are queued before the
289 // channel they are addressed to is ready.
290 PendingChannelMap pending_tls_channel_id_channels_
;
291 // A set of channel IDs waiting for user permission to cross the border
292 // between an incognito page and an app or extension, and any pending messages
293 // queued to be sent on those channels.
294 PendingChannelMap pending_incognito_channels_
;
295 PendingLazyBackgroundPageChannelMap pending_lazy_background_page_channels_
;
296 MessagePropertyProvider property_provider_
;
298 // Weak pointer. Guaranteed to outlive this class.
299 LazyBackgroundTaskQueue
* lazy_background_task_queue_
;
301 base::WeakPtrFactory
<MessageService
> weak_factory_
;
303 DISALLOW_COPY_AND_ASSIGN(MessageService
);
306 } // namespace extensions
308 #endif // CHROME_BROWSER_EXTENSIONS_API_MESSAGING_MESSAGE_SERVICE_H_