1 // Copyright 2013 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 #include "content/child/npapi/np_channel_base.h"
7 #include "base/auto_reset.h"
8 #include "base/containers/hash_tables.h"
9 #include "base/files/scoped_file.h"
10 #include "base/lazy_instance.h"
11 #include "base/single_thread_task_runner.h"
12 #include "base/strings/string_number_conversions.h"
13 #include "base/threading/thread_local.h"
14 #include "ipc/ipc_sync_message.h"
17 #include "base/files/file_util.h"
18 #include "ipc/ipc_channel_posix.h"
25 typedef base::hash_map
<std::string
, scoped_refptr
<NPChannelBase
> > ChannelMap
;
27 struct ChannelGlobals
{
28 ChannelMap channel_map
;
29 scoped_refptr
<NPChannelBase
> current_channel
;
32 #if defined(OS_ANDROID)
33 // Workaround for http://crbug.com/298179 - NPChannelBase is only intended
34 // for use on one thread per process. Using TLS to store the globals removes the
35 // worst thread hostility in this class, especially needed for webview which
36 // runs in single-process mode. TODO(joth): Make a complete fix, most likely
37 // as part of addressing http://crbug.com/258510.
38 base::LazyInstance
<base::ThreadLocalPointer
<ChannelGlobals
> >::Leaky
39 g_channels_tls_ptr
= LAZY_INSTANCE_INITIALIZER
;
41 ChannelGlobals
* GetChannelGlobals() {
42 ChannelGlobals
* globals
= g_channels_tls_ptr
.Get().Get();
44 globals
= new ChannelGlobals
;
45 g_channels_tls_ptr
.Get().Set(globals
);
52 base::LazyInstance
<ChannelGlobals
>::Leaky g_channels_globals
=
53 LAZY_INSTANCE_INITIALIZER
;
55 ChannelGlobals
* GetChannelGlobals() { return g_channels_globals
.Pointer(); }
59 ChannelMap
* GetChannelMap() {
60 return &GetChannelGlobals()->channel_map
;
65 NPChannelBase
* NPChannelBase::GetChannel(
66 const IPC::ChannelHandle
& channel_handle
,
67 IPC::Channel::Mode mode
,
68 ChannelFactory factory
,
69 base::SingleThreadTaskRunner
* ipc_task_runner
,
71 base::WaitableEvent
* shutdown_event
) {
73 // On POSIX the channel_handle conveys an FD (socket) which is duped by the
74 // kernel during the IPC message exchange (via the SCM_RIGHTS mechanism).
75 // Ensure we do not leak this FD.
76 base::ScopedFD
fd(channel_handle
.socket
.auto_close
?
77 channel_handle
.socket
.fd
: -1);
80 scoped_refptr
<NPChannelBase
> channel
;
81 std::string channel_key
= channel_handle
.name
;
82 ChannelMap::const_iterator iter
= GetChannelMap()->find(channel_key
);
83 if (iter
== GetChannelMap()->end()) {
86 channel
= iter
->second
;
89 DCHECK(channel
.get() != NULL
);
91 if (!channel
->channel_valid()) {
92 channel
->channel_handle_
= channel_handle
;
94 ignore_result(fd
.release());
96 if (mode
& IPC::Channel::MODE_SERVER_FLAG
) {
97 channel
->channel_handle_
.name
=
98 IPC::Channel::GenerateVerifiedChannelID(channel_key
);
100 channel
->mode_
= mode
;
101 if (channel
->Init(ipc_task_runner
, create_pipe_now
, shutdown_event
)) {
102 (*GetChannelMap())[channel_key
] = channel
;
108 return channel
.get();
111 void NPChannelBase::Broadcast(IPC::Message
* message
) {
112 for (ChannelMap::iterator iter
= GetChannelMap()->begin();
113 iter
!= GetChannelMap()->end();
115 iter
->second
->Send(new IPC::Message(*message
));
120 NPChannelBase::NPChannelBase()
121 : mode_(IPC::Channel::MODE_NONE
),
122 non_npobject_count_(0),
124 in_remove_route_(false),
125 default_owner_(NULL
),
126 channel_valid_(false),
127 in_unblock_dispatch_(0),
128 send_unblocking_only_during_unblock_dispatch_(false) {
131 NPChannelBase::~NPChannelBase() {
132 // TODO(wez): Establish why these would ever be non-empty at teardown.
133 //DCHECK(npobject_listeners_.empty());
134 //DCHECK(proxy_map_.empty());
135 //DCHECK(stub_map_.empty());
136 DCHECK(owner_to_route_
.empty());
137 DCHECK(route_to_owner_
.empty());
140 NPChannelBase
* NPChannelBase::GetCurrentChannel() {
141 return GetChannelGlobals()->current_channel
.get();
144 void NPChannelBase::CleanupChannels() {
145 // Make a copy of the references as we can't iterate the map since items will
146 // be removed from it as we clean them up.
147 std::vector
<scoped_refptr
<NPChannelBase
> > channels
;
148 for (ChannelMap::const_iterator iter
= GetChannelMap()->begin();
149 iter
!= GetChannelMap()->end();
151 channels
.push_back(iter
->second
);
154 for (size_t i
= 0; i
< channels
.size(); ++i
)
155 channels
[i
]->CleanUp();
157 // This will clean up channels added to the map for which subsequent
158 // AddRoute wasn't called
159 GetChannelMap()->clear();
162 NPObjectBase
* NPChannelBase::GetNPObjectListenerForRoute(int route_id
) {
163 ListenerMap::iterator iter
= npobject_listeners_
.find(route_id
);
164 if (iter
== npobject_listeners_
.end()) {
165 DLOG(WARNING
) << "Invalid route id passed in:" << route_id
;
171 base::WaitableEvent
* NPChannelBase::GetModalDialogEvent(int render_view_id
) {
175 bool NPChannelBase::Init(base::SingleThreadTaskRunner
* ipc_task_runner
,
176 bool create_pipe_now
,
177 base::WaitableEvent
* shutdown_event
) {
178 #if defined(OS_POSIX)
179 // Attempting to initialize with an invalid channel handle.
180 // See http://crbug.com/97285 for details.
181 if (mode_
== IPC::Channel::MODE_CLIENT
&& -1 == channel_handle_
.socket
.fd
)
186 IPC::SyncChannel::Create(channel_handle_
, mode_
, this, ipc_task_runner
,
187 create_pipe_now
, shutdown_event
);
189 #if defined(OS_POSIX)
190 // Check the validity of fd for bug investigation. Remove after fixed.
191 // See crbug.com/97285 for details.
192 if (mode_
== IPC::Channel::MODE_SERVER
)
193 CHECK_NE(-1, channel_
->GetClientFileDescriptor());
196 channel_valid_
= true;
200 bool NPChannelBase::Send(IPC::Message
* message
) {
202 VLOG(1) << "Channel is NULL; dropping message";
207 if (send_unblocking_only_during_unblock_dispatch_
&&
208 in_unblock_dispatch_
== 0 &&
209 message
->is_sync()) {
210 message
->set_unblock(false);
213 return channel_
->Send(message
);
216 int NPChannelBase::Count() {
217 return static_cast<int>(GetChannelMap()->size());
220 bool NPChannelBase::OnMessageReceived(const IPC::Message
& message
) {
221 // Push this channel as the current channel being processed. This also forms
222 // a stack of scoped_refptr avoiding ourselves (or any instance higher
223 // up the callstack) from being deleted while processing a message.
224 base::AutoReset
<scoped_refptr
<NPChannelBase
> > keep_alive(
225 &GetChannelGlobals()->current_channel
, this);
228 if (message
.should_unblock())
229 in_unblock_dispatch_
++;
230 if (message
.routing_id() == MSG_ROUTING_CONTROL
) {
231 handled
= OnControlMessageReceived(message
);
233 handled
= router_
.RouteMessage(message
);
234 if (!handled
&& message
.is_sync()) {
235 // The listener has gone away, so we must respond or else the caller will
236 // hang waiting for a reply.
237 IPC::Message
* reply
= IPC::SyncMessage::GenerateReply(&message
);
238 reply
->set_reply_error();
242 if (message
.should_unblock())
243 in_unblock_dispatch_
--;
248 void NPChannelBase::OnChannelConnected(int32 peer_pid
) {
249 peer_pid_
= peer_pid
;
252 void NPChannelBase::AddRoute(int route_id
,
253 IPC::Listener
* listener
,
254 NPObjectBase
* npobject
) {
256 npobject_listeners_
[route_id
] = npobject
;
258 non_npobject_count_
++;
261 router_
.AddRoute(route_id
, listener
);
264 void NPChannelBase::RemoveRoute(int route_id
) {
265 router_
.RemoveRoute(route_id
);
267 ListenerMap::iterator iter
= npobject_listeners_
.find(route_id
);
268 if (iter
!= npobject_listeners_
.end()) {
269 // This was an NPObject proxy or stub, it's not involved in the refcounting.
271 // If this RemoveRoute call from the NPObject is a result of us calling
272 // OnChannelError below, don't call erase() here because that'll corrupt
273 // the iterator below.
274 if (in_remove_route_
) {
277 npobject_listeners_
.erase(iter
);
283 non_npobject_count_
--;
284 DCHECK(non_npobject_count_
>= 0);
286 if (!non_npobject_count_
) {
287 base::AutoReset
<bool> auto_reset_in_remove_route(&in_remove_route_
, true);
288 for (ListenerMap::iterator npobj_iter
= npobject_listeners_
.begin();
289 npobj_iter
!= npobject_listeners_
.end(); ++npobj_iter
) {
290 if (npobj_iter
->second
) {
291 npobj_iter
->second
->GetChannelListener()->OnChannelError();
295 for (ChannelMap::iterator iter
= GetChannelMap()->begin();
296 iter
!= GetChannelMap()->end(); ++iter
) {
297 if (iter
->second
.get() == this) {
298 GetChannelMap()->erase(iter
);
307 bool NPChannelBase::OnControlMessageReceived(const IPC::Message
& msg
) {
309 "should override in subclass if you care about control messages";
313 void NPChannelBase::OnChannelError() {
314 channel_valid_
= false;
316 // TODO(shess): http://crbug.com/97285
317 // Once an error is seen on a channel, remap the channel to prevent
318 // it from being vended again. Keep the channel in the map so
319 // RemoveRoute() can clean things up correctly.
320 for (ChannelMap::iterator iter
= GetChannelMap()->begin();
321 iter
!= GetChannelMap()->end(); ++iter
) {
322 if (iter
->second
.get() == this) {
323 // Insert new element before invalidating |iter|.
324 (*GetChannelMap())[iter
->first
+ "-error"] = iter
->second
;
325 GetChannelMap()->erase(iter
);
331 void NPChannelBase::AddMappingForNPObjectProxy(int route_id
,
333 proxy_map_
[route_id
] = object
;
336 void NPChannelBase::RemoveMappingForNPObjectProxy(int route_id
) {
337 proxy_map_
.erase(route_id
);
340 void NPChannelBase::AddMappingForNPObjectStub(int route_id
,
342 DCHECK(object
!= NULL
);
343 stub_map_
[object
] = route_id
;
346 void NPChannelBase::RemoveMappingForNPObjectStub(int route_id
,
348 DCHECK(object
!= NULL
);
349 stub_map_
.erase(object
);
352 void NPChannelBase::AddMappingForNPObjectOwner(int route_id
,
353 struct _NPP
* owner
) {
354 DCHECK(owner
!= NULL
);
355 route_to_owner_
[route_id
] = owner
;
356 owner_to_route_
[owner
] = route_id
;
359 void NPChannelBase::SetDefaultNPObjectOwner(struct _NPP
* owner
) {
360 DCHECK(owner
!= NULL
);
361 default_owner_
= owner
;
364 void NPChannelBase::RemoveMappingForNPObjectOwner(int route_id
) {
365 DCHECK(route_to_owner_
.find(route_id
) != route_to_owner_
.end());
366 owner_to_route_
.erase(route_to_owner_
[route_id
]);
367 route_to_owner_
.erase(route_id
);
370 NPObject
* NPChannelBase::GetExistingNPObjectProxy(int route_id
) {
371 ProxyMap::iterator iter
= proxy_map_
.find(route_id
);
372 return iter
!= proxy_map_
.end() ? iter
->second
: NULL
;
375 int NPChannelBase::GetExistingRouteForNPObjectStub(NPObject
* npobject
) {
376 StubMap::iterator iter
= stub_map_
.find(npobject
);
377 return iter
!= stub_map_
.end() ? iter
->second
: MSG_ROUTING_NONE
;
380 NPP
NPChannelBase::GetExistingNPObjectOwner(int route_id
) {
381 RouteToOwnerMap::iterator iter
= route_to_owner_
.find(route_id
);
382 return iter
!= route_to_owner_
.end() ? iter
->second
: default_owner_
;
385 int NPChannelBase::GetExistingRouteForNPObjectOwner(NPP owner
) {
386 OwnerToRouteMap::iterator iter
= owner_to_route_
.find(owner
);
387 return iter
!= owner_to_route_
.end() ? iter
->second
: MSG_ROUTING_NONE
;
390 } // namespace content