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.
4
5#ifndef CHROME_BROWSER_EXTENSIONS_API_MESSAGING_MESSAGE_SERVICE_H_
6#define CHROME_BROWSER_EXTENSIONS_API_MESSAGING_MESSAGE_SERVICE_H_
7
8#include <map>
9#include <set>
10#include <string>
11#include <vector>
12
13#include "base/compiler_specific.h"
14#include "base/memory/scoped_ptr.h"
15#include "base/memory/weak_ptr.h"
16#include "chrome/browser/extensions/api/messaging/message_property_provider.h"
17#include "chrome/browser/extensions/api/messaging/native_message_process_host.h"
18#include "content/public/browser/notification_observer.h"
19#include "content/public/browser/notification_registrar.h"
20#include "extensions/browser/browser_context_keyed_api_factory.h"
21#include "extensions/common/api/messaging/message.h"
22
23class GURL;
24class Profile;
25
26namespace base {
27class DictionaryValue;
28}
29
30namespace content {
31class BrowserContext;
32class RenderProcessHost;
33class WebContents;
34}
35
36namespace extensions {
37class Extension;
38class ExtensionHost;
39class LazyBackgroundTaskQueue;
40
41// This class manages message and event passing between renderer processes.
42// It maintains a list of processes that are listening to events and a set of
43// open channels.
44//
45// Messaging works this way:
46// - An extension-owned script context (like a background page or a content
47//   script) adds an event listener to the "onConnect" event.
48// - Another context calls "runtime.connect()" to open a channel to the
49// extension process, or an extension context calls "tabs.connect(tabId)" to
50// open a channel to the content scripts for the given tab.  The EMS notifies
51// the target process/tab, which then calls the onConnect event in every
52// context owned by the connecting extension in that process/tab.
53// - Once the channel is established, either side can call postMessage to send
54// a message to the opposite side of the channel, which may have multiple
55// listeners.
56//
57// Terminology:
58// channel: connection between two ports
59// port: an IPC::Message::Process interface and an optional routing_id (in the
60// case that the port is a tab).  The Process is usually either a
61// RenderProcessHost or a RenderViewHost.
62class MessageService : public BrowserContextKeyedAPI,
63                       public content::NotificationObserver,
64                       public NativeMessageProcessHost::Client {
65 public:
66  // A messaging channel. Note that the opening port can be the same as the
67  // receiver, if an extension background page wants to talk to its tab (for
68  // example).
69  struct MessageChannel;
70
71  // One side of the communication handled by extensions::MessageService.
72  class MessagePort {
73   public:
74    virtual ~MessagePort() {}
75    // Notify the port that the channel has been opened.
76    virtual void DispatchOnConnect(int dest_port_id,
77                                   const std::string& channel_name,
78                                   const base::DictionaryValue& source_tab,
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) {}
83
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) {}
88
89    // Dispatch a message to this end of the communication.
90    virtual void DispatchOnMessage(const Message& message,
91                                   int target_port_id) = 0;
92
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() {}
97
98    // Get the RenderProcessHost (if any) associated with the port.
99    virtual content::RenderProcessHost* GetRenderProcessHost();
100
101   protected:
102    MessagePort() {}
103
104   private:
105    DISALLOW_COPY_AND_ASSIGN(MessagePort);
106  };
107
108  // Allocates a pair of port ids.
109  // NOTE: this can be called from any thread.
110  static void AllocatePortIdPair(int* port1, int* port2);
111
112  explicit MessageService(content::BrowserContext* context);
113  virtual ~MessageService();
114
115  // BrowserContextKeyedAPI implementation.
116  static BrowserContextKeyedAPIFactory<MessageService>* GetFactoryInstance();
117
118  // Convenience method to get the MessageService for a browser context.
119  static MessageService* Get(content::BrowserContext* context);
120
121  // Given an extension's ID, opens a channel between the given renderer "port"
122  // and every listening context owned by that extension. |channel_name| is
123  // an optional identifier for use by extension developers.
124  void OpenChannelToExtension(
125      int source_process_id, int source_routing_id, int receiver_port_id,
126      const std::string& source_extension_id,
127      const std::string& target_extension_id,
128      const GURL& source_url,
129      const std::string& channel_name,
130      bool include_tls_channel_id);
131
132  // Same as above, but opens a channel to the tab with the given ID.  Messages
133  // are restricted to that tab, so if there are multiple tabs in that process,
134  // only the targeted tab will receive messages.
135  void OpenChannelToTab(
136      int source_process_id, int source_routing_id, int receiver_port_id,
137      int tab_id, const std::string& extension_id,
138      const std::string& channel_name);
139
140  void OpenChannelToNativeApp(
141      int source_process_id,
142      int source_routing_id,
143      int receiver_port_id,
144      const std::string& source_extension_id,
145      const std::string& native_app_name);
146
147  // Closes the message channel associated with the given port, and notifies
148  // the other side.
149  virtual void CloseChannel(int port_id,
150                            const std::string& error_message) OVERRIDE;
151
152  // Enqueues a message on a pending channel, or sends a message to the given
153  // port if the channel isn't pending.
154  void PostMessage(int port_id, const Message& message);
155
156  // NativeMessageProcessHost::Client
157  virtual void PostMessageFromNativeProcess(
158      int port_id,
159      const std::string& message) OVERRIDE;
160
161 private:
162  friend class MockMessageService;
163  friend class BrowserContextKeyedAPIFactory<MessageService>;
164  struct OpenChannelParams;
165
166  // A map of channel ID to its channel object.
167  typedef std::map<int, MessageChannel*> MessageChannelMap;
168
169  typedef std::pair<int, Message> PendingMessage;
170  typedef std::vector<PendingMessage> PendingMessagesQueue;
171  // A set of channel IDs waiting for TLS channel IDs to complete opening,
172  // and any pending messages queued to be sent on those channels.
173  typedef std::map<int, PendingMessagesQueue> PendingTlsChannelIdMap;
174
175  // A map of channel ID to information about the extension that is waiting
176  // for that channel to open. Used for lazy background pages.
177  typedef std::string ExtensionID;
178  typedef std::pair<content::BrowserContext*, ExtensionID>
179      PendingLazyBackgroundPageChannel;
180  typedef std::map<int, PendingLazyBackgroundPageChannel>
181      PendingLazyBackgroundPageChannelMap;
182
183  // Common among OpenChannel* variants.
184  bool OpenChannelImpl(scoped_ptr<OpenChannelParams> params);
185
186  void CloseChannelImpl(MessageChannelMap::iterator channel_iter,
187                        int port_id,
188                        const std::string& error_message,
189                        bool notify_other_port);
190
191  // Have MessageService take ownership of |channel|, and remove any pending
192  // channels with the same id.
193  void AddChannel(MessageChannel* channel, int receiver_port_id);
194
195  // content::NotificationObserver interface.
196  virtual void Observe(int type,
197                       const content::NotificationSource& source,
198                       const content::NotificationDetails& details) OVERRIDE;
199
200  // A process that might be in our list of channels has closed.
201  void OnProcessClosed(content::RenderProcessHost* process);
202
203  void GotChannelID(scoped_ptr<OpenChannelParams> params,
204                    const std::string& tls_channel_id);
205
206  // Enqueues a message on a pending channel.
207  void EnqueuePendingMessage(int port_id, int channel_id,
208                             const Message& message);
209
210  // Enqueues a message on a channel pending on a lazy background page load.
211  void EnqueuePendingMessageForLazyBackgroundLoad(int port_id,
212                                                  int channel_id,
213                                                  const Message& message);
214
215  // Immediately sends a message to the given port.
216  void DispatchMessage(int port_id, MessageChannel* channel,
217                       const Message& message);
218
219  // Potentially registers a pending task with the LazyBackgroundTaskQueue
220  // to open a channel. Returns true if a task was queued.
221  // Takes ownership of |params| if true is returned.
222  bool MaybeAddPendingLazyBackgroundPageOpenChannelTask(
223      content::BrowserContext* context,
224      const Extension* extension,
225      OpenChannelParams* params);
226
227  // Callbacks for LazyBackgroundTaskQueue tasks. The queue passes in an
228  // ExtensionHost to its task callbacks, though some of our callbacks don't
229  // use that argument.
230  void PendingLazyBackgroundPageOpenChannel(
231      scoped_ptr<OpenChannelParams> params,
232      int source_process_id,
233      extensions::ExtensionHost* host);
234  void PendingLazyBackgroundPageCloseChannel(int port_id,
235                                             const std::string& error_message,
236                                             extensions::ExtensionHost* host) {
237    if (host)
238      CloseChannel(port_id, error_message);
239  }
240  void PendingLazyBackgroundPagePostMessage(int port_id,
241                                            const Message& message,
242                                            extensions::ExtensionHost* host) {
243    if (host)
244      PostMessage(port_id, message);
245  }
246
247  // Immediate dispatches a disconnect to |source| for |port_id|. Sets source's
248  // runtime.lastMessage to |error_message|, if any.
249  void DispatchOnDisconnect(content::RenderProcessHost* source,
250                            int port_id,
251                            const std::string& error_message);
252
253  // BrowserContextKeyedAPI implementation.
254  static const char* service_name() {
255    return "MessageService";
256  }
257  static const bool kServiceRedirectedInIncognito = true;
258  static const bool kServiceIsCreatedWithBrowserContext = false;
259  static const bool kServiceIsNULLWhileTesting = true;
260
261  content::NotificationRegistrar registrar_;
262  MessageChannelMap channels_;
263  PendingTlsChannelIdMap pending_tls_channel_id_channels_;
264  PendingLazyBackgroundPageChannelMap pending_lazy_background_page_channels_;
265  MessagePropertyProvider property_provider_;
266
267  // Weak pointer. Guaranteed to outlive this class.
268  LazyBackgroundTaskQueue* lazy_background_task_queue_;
269
270  base::WeakPtrFactory<MessageService> weak_factory_;
271
272  DISALLOW_COPY_AND_ASSIGN(MessageService);
273};
274
275}  // namespace extensions
276
277#endif  // CHROME_BROWSER_EXTENSIONS_API_MESSAGING_MESSAGE_SERVICE_H_
278