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 IPC_MESSAGE_ROUTER_H_
6 #define IPC_MESSAGE_ROUTER_H_
7 
8 #include <stdint.h>
9 
10 #include "base/component_export.h"
11 #include "base/containers/id_map.h"
12 #include "base/macros.h"
13 #include "ipc/ipc_listener.h"
14 #include "ipc/ipc_sender.h"
15 
16 // The MessageRouter handles all incoming messages sent to it by routing them
17 // to the correct listener.  Routing is based on the Message's routing ID.
18 // Since routing IDs are typically assigned asynchronously by the browser
19 // process, the MessageRouter has the notion of pending IDs for listeners that
20 // have not yet been assigned a routing ID.
21 //
22 // When a message arrives, the routing ID is used to index the set of routes to
23 // find a listener.  If a listener is found, then the message is passed to it.
24 // Otherwise, the message is ignored if its routing ID is not equal to
25 // MSG_ROUTING_CONTROL.
26 //
27 // The MessageRouter supports the IPC::Sender interface for outgoing messages,
28 // but does not define a meaningful implementation of it.  The subclass of
29 // MessageRouter is intended to provide that if appropriate.
30 //
31 // The MessageRouter can be used as a concrete class provided its Send method
32 // is not called and it does not receive any control messages.
33 
34 namespace IPC {
35 
COMPONENT_EXPORT(IPC)36 class COMPONENT_EXPORT(IPC) MessageRouter : public Listener, public Sender {
37  public:
38   MessageRouter();
39   ~MessageRouter() override;
40 
41   // Implemented by subclasses to handle control messages
42   virtual bool OnControlMessageReceived(const Message& msg);
43 
44   // Listener implementation:
45   bool OnMessageReceived(const Message& msg) override;
46 
47   // Like OnMessageReceived, except it only handles routed messages.  Returns
48   // true if the message was dispatched, or false if there was no listener for
49   // that route id.
50   virtual bool RouteMessage(const Message& msg);
51 
52   // Sender implementation:
53   bool Send(Message* msg) override;
54 
55   // Called to add a listener for a particular message routing ID.
56   // Returns true if succeeded.
57   bool AddRoute(int32_t routing_id, Listener* listener);
58 
59   // Called to remove a listener for a particular message routing ID.
60   void RemoveRoute(int32_t routing_id);
61 
62   // Returns the Listener associated with |routing_id|.
63   Listener* GetRoute(int32_t routing_id);
64 
65  private:
66   // A list of all listeners with assigned routing IDs.
67   base::IDMap<Listener*> routes_;
68 
69   DISALLOW_COPY_AND_ASSIGN(MessageRouter);
70 };
71 
72 }  // namespace IPC
73 
74 #endif  // IPC_MESSAGE_ROUTER_H_
75