1 // Copyright 2014 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 "ipc/mojo/ipc_channel_mojo.h"
8 #include "base/bind_helpers.h"
9 #include "base/lazy_instance.h"
10 #include "ipc/ipc_listener.h"
11 #include "ipc/ipc_logging.h"
12 #include "ipc/ipc_message_attachment_set.h"
13 #include "ipc/ipc_message_macros.h"
14 #include "ipc/mojo/client_channel.mojom.h"
15 #include "ipc/mojo/ipc_mojo_bootstrap.h"
16 #include "ipc/mojo/ipc_mojo_handle_attachment.h"
17 #include "third_party/mojo/src/mojo/edk/embedder/embedder.h"
18 #include "third_party/mojo/src/mojo/public/cpp/bindings/error_handler.h"
20 #if defined(OS_POSIX) && !defined(OS_NACL)
21 #include "ipc/ipc_platform_file_attachment_posix.h"
28 class MojoChannelFactory
: public ChannelFactory
{
30 MojoChannelFactory(ChannelMojo::Delegate
* delegate
,
31 ChannelHandle channel_handle
,
33 : delegate_(delegate
), channel_handle_(channel_handle
), mode_(mode
) {}
35 std::string
GetName() const override
{
36 return channel_handle_
.name
;
39 scoped_ptr
<Channel
> BuildChannel(Listener
* listener
) override
{
40 return ChannelMojo::Create(delegate_
, channel_handle_
, mode_
, listener
);
44 ChannelMojo::Delegate
* delegate_
;
45 ChannelHandle channel_handle_
;
49 //------------------------------------------------------------------------------
51 class ClientChannelMojo
: public ChannelMojo
,
53 public mojo::ErrorHandler
{
55 ClientChannelMojo(ChannelMojo::Delegate
* delegate
,
56 const ChannelHandle
& handle
,
58 ~ClientChannelMojo() override
;
59 // MojoBootstrap::Delegate implementation
60 void OnPipeAvailable(mojo::embedder::ScopedPlatformHandle handle
) override
;
61 // mojo::ErrorHandler implementation
62 void OnConnectionError() override
;
63 // ClientChannel implementation
65 mojo::ScopedMessagePipeHandle pipe
,
67 const mojo::Callback
<void(int32_t)>& callback
) override
;
70 mojo::Binding
<ClientChannel
> binding_
;
72 DISALLOW_COPY_AND_ASSIGN(ClientChannelMojo
);
75 ClientChannelMojo::ClientChannelMojo(ChannelMojo::Delegate
* delegate
,
76 const ChannelHandle
& handle
,
78 : ChannelMojo(delegate
, handle
, Channel::MODE_CLIENT
, listener
),
82 ClientChannelMojo::~ClientChannelMojo() {
85 void ClientChannelMojo::OnPipeAvailable(
86 mojo::embedder::ScopedPlatformHandle handle
) {
87 binding_
.Bind(CreateMessagingPipe(handle
.Pass()));
90 void ClientChannelMojo::OnConnectionError() {
91 listener()->OnChannelError();
94 void ClientChannelMojo::Init(
95 mojo::ScopedMessagePipeHandle pipe
,
97 const mojo::Callback
<void(int32_t)>& callback
) {
98 InitMessageReader(pipe
.Pass(), static_cast<base::ProcessId
>(peer_pid
));
99 callback
.Run(GetSelfPID());
102 //------------------------------------------------------------------------------
104 class ServerChannelMojo
: public ChannelMojo
, public mojo::ErrorHandler
{
106 ServerChannelMojo(ChannelMojo::Delegate
* delegate
,
107 const ChannelHandle
& handle
,
109 ~ServerChannelMojo() override
;
111 // MojoBootstrap::Delegate implementation
112 void OnPipeAvailable(mojo::embedder::ScopedPlatformHandle handle
) override
;
113 // mojo::ErrorHandler implementation
114 void OnConnectionError() override
;
116 void Close() override
;
119 // ClientChannelClient implementation
120 void ClientChannelWasInitialized(int32_t peer_pid
);
122 mojo::InterfacePtr
<ClientChannel
> client_channel_
;
123 mojo::ScopedMessagePipeHandle message_pipe_
;
125 DISALLOW_COPY_AND_ASSIGN(ServerChannelMojo
);
128 ServerChannelMojo::ServerChannelMojo(ChannelMojo::Delegate
* delegate
,
129 const ChannelHandle
& handle
,
131 : ChannelMojo(delegate
, handle
, Channel::MODE_SERVER
, listener
) {
134 ServerChannelMojo::~ServerChannelMojo() {
138 void ServerChannelMojo::OnPipeAvailable(
139 mojo::embedder::ScopedPlatformHandle handle
) {
140 mojo::ScopedMessagePipeHandle peer
;
141 MojoResult create_result
=
142 mojo::CreateMessagePipe(nullptr, &message_pipe_
, &peer
);
143 if (create_result
!= MOJO_RESULT_OK
) {
144 LOG(WARNING
) << "mojo::CreateMessagePipe failed: " << create_result
;
145 listener()->OnChannelError();
149 client_channel_
.Bind(CreateMessagingPipe(handle
.Pass()));
150 client_channel_
.set_error_handler(this);
151 client_channel_
->Init(
153 static_cast<int32_t>(GetSelfPID()),
154 base::Bind(&ServerChannelMojo::ClientChannelWasInitialized
,
155 base::Unretained(this)));
158 void ServerChannelMojo::ClientChannelWasInitialized(int32_t peer_pid
) {
159 InitMessageReader(message_pipe_
.Pass(), peer_pid
);
162 void ServerChannelMojo::OnConnectionError() {
163 listener()->OnChannelError();
166 void ServerChannelMojo::Close() {
167 client_channel_
.reset();
168 message_pipe_
.reset();
169 ChannelMojo::Close();
172 #if defined(OS_POSIX) && !defined(OS_NACL)
174 base::ScopedFD
TakeOrDupFile(internal::PlatformFileAttachment
* attachment
) {
175 return attachment
->Owns() ? base::ScopedFD(attachment
->TakePlatformFile())
176 : base::ScopedFD(dup(attachment
->file()));
183 //------------------------------------------------------------------------------
185 void ChannelMojo::ChannelInfoDeleter::operator()(
186 mojo::embedder::ChannelInfo
* ptr
) const {
187 mojo::embedder::DestroyChannelOnIOThread(ptr
);
190 //------------------------------------------------------------------------------
193 bool ChannelMojo::ShouldBeUsed() {
194 // TODO(morrita): Remove this if it sticks.
199 scoped_ptr
<ChannelMojo
> ChannelMojo::Create(ChannelMojo::Delegate
* delegate
,
200 const ChannelHandle
& channel_handle
,
202 Listener
* listener
) {
204 case Channel::MODE_CLIENT
:
205 return make_scoped_ptr(
206 new ClientChannelMojo(delegate
, channel_handle
, listener
));
207 case Channel::MODE_SERVER
:
208 return make_scoped_ptr(
209 new ServerChannelMojo(delegate
, channel_handle
, listener
));
217 scoped_ptr
<ChannelFactory
> ChannelMojo::CreateServerFactory(
218 ChannelMojo::Delegate
* delegate
,
219 const ChannelHandle
& channel_handle
) {
220 return make_scoped_ptr(
221 new MojoChannelFactory(delegate
, channel_handle
, Channel::MODE_SERVER
));
225 scoped_ptr
<ChannelFactory
> ChannelMojo::CreateClientFactory(
226 ChannelMojo::Delegate
* delegate
,
227 const ChannelHandle
& channel_handle
) {
228 return make_scoped_ptr(
229 new MojoChannelFactory(delegate
, channel_handle
, Channel::MODE_CLIENT
));
232 ChannelMojo::ChannelMojo(ChannelMojo::Delegate
* delegate
,
233 const ChannelHandle
& handle
,
238 peer_pid_(base::kNullProcessId
),
239 weak_factory_(this) {
240 // Create MojoBootstrap after all members are set as it touches
241 // ChannelMojo from a different thread.
242 bootstrap_
= MojoBootstrap::Create(handle
, mode
, this);
244 if (delegate
->GetIOTaskRunner() ==
245 base::MessageLoop::current()->message_loop_proxy()) {
246 InitDelegate(delegate
);
248 delegate
->GetIOTaskRunner()->PostTask(
251 &ChannelMojo::InitDelegate
, base::Unretained(this), delegate
));
256 ChannelMojo::~ChannelMojo() {
260 void ChannelMojo::InitDelegate(ChannelMojo::Delegate
* delegate
) {
262 new ScopedIPCSupport(base::MessageLoop::current()->task_runner()));
263 delegate_
= delegate
->ToWeakPtr();
264 delegate_
->OnChannelCreated(weak_factory_
.GetWeakPtr());
267 mojo::ScopedMessagePipeHandle
ChannelMojo::CreateMessagingPipe(
268 mojo::embedder::ScopedPlatformHandle handle
) {
269 DCHECK(!channel_info_
.get());
270 mojo::embedder::ChannelInfo
* channel_info
;
271 mojo::ScopedMessagePipeHandle pipe
=
272 mojo::embedder::CreateChannelOnIOThread(handle
.Pass(), &channel_info
);
273 channel_info_
.reset(channel_info
);
277 bool ChannelMojo::Connect() {
278 DCHECK(!message_reader_
);
279 return bootstrap_
->Connect();
282 void ChannelMojo::Close() {
283 message_reader_
.reset();
284 channel_info_
.reset();
285 ipc_support_
.reset();
288 void ChannelMojo::OnBootstrapError() {
289 listener_
->OnChannelError();
292 void ChannelMojo::InitMessageReader(mojo::ScopedMessagePipeHandle pipe
,
295 make_scoped_ptr(new internal::MessagePipeReader(pipe
.Pass(), this));
297 for (size_t i
= 0; i
< pending_messages_
.size(); ++i
) {
298 bool sent
= message_reader_
->Send(make_scoped_ptr(pending_messages_
[i
]));
299 pending_messages_
[i
] = nullptr;
301 pending_messages_
.clear();
302 listener_
->OnChannelError();
307 pending_messages_
.clear();
309 set_peer_pid(peer_pid
);
310 listener_
->OnChannelConnected(static_cast<int32_t>(GetPeerPID()));
312 message_reader_
->ReadMessagesThenWait();
315 void ChannelMojo::OnPipeClosed(internal::MessagePipeReader
* reader
) {
319 void ChannelMojo::OnPipeError(internal::MessagePipeReader
* reader
) {
320 listener_
->OnChannelError();
324 bool ChannelMojo::Send(Message
* message
) {
325 if (!message_reader_
) {
326 pending_messages_
.push_back(message
);
330 return message_reader_
->Send(make_scoped_ptr(message
));
333 base::ProcessId
ChannelMojo::GetPeerPID() const {
337 base::ProcessId
ChannelMojo::GetSelfPID() const {
338 return bootstrap_
->GetSelfPID();
341 void ChannelMojo::OnClientLaunched(base::ProcessHandle handle
) {
342 bootstrap_
->OnClientLaunched(handle
);
345 void ChannelMojo::OnMessageReceived(Message
& message
) {
346 TRACE_EVENT2("ipc,toplevel", "ChannelMojo::OnMessageReceived",
347 "class", IPC_MESSAGE_ID_CLASS(message
.type()),
348 "line", IPC_MESSAGE_ID_LINE(message
.type()));
349 listener_
->OnMessageReceived(message
);
350 if (message
.dispatch_error())
351 listener_
->OnBadMessageReceived(message
);
354 #if defined(OS_POSIX) && !defined(OS_NACL)
355 int ChannelMojo::GetClientFileDescriptor() const {
356 return bootstrap_
->GetClientFileDescriptor();
359 base::ScopedFD
ChannelMojo::TakeClientFileDescriptor() {
360 return bootstrap_
->TakeClientFileDescriptor();
362 #endif // defined(OS_POSIX) && !defined(OS_NACL)
365 MojoResult
ChannelMojo::ReadFromMessageAttachmentSet(
367 std::vector
<MojoHandle
>* handles
) {
368 // We dup() the handles in IPC::Message to transmit.
369 // IPC::MessageAttachmentSet has intricate lifecycle semantics
370 // of FDs, so just to dup()-and-own them is the safest option.
371 if (message
->HasAttachments()) {
372 MessageAttachmentSet
* set
= message
->attachment_set();
373 for (unsigned i
= 0; i
< set
->size(); ++i
) {
374 scoped_refptr
<MessageAttachment
> attachment
= set
->GetAttachmentAt(i
);
375 switch (attachment
->GetType()) {
376 case MessageAttachment::TYPE_PLATFORM_FILE
:
377 #if defined(OS_POSIX) && !defined(OS_NACL)
379 base::ScopedFD file
=
380 TakeOrDupFile(static_cast<IPC::internal::PlatformFileAttachment
*>(
382 if (!file
.is_valid()) {
383 DPLOG(WARNING
) << "Failed to dup FD to transmit.";
385 return MOJO_RESULT_UNKNOWN
;
388 MojoHandle wrapped_handle
;
389 MojoResult wrap_result
= CreatePlatformHandleWrapper(
390 mojo::embedder::ScopedPlatformHandle(
391 mojo::embedder::PlatformHandle(file
.release())),
393 if (MOJO_RESULT_OK
!= wrap_result
) {
394 LOG(WARNING
) << "Pipe failed to wrap handles. Closing: "
400 handles
->push_back(wrapped_handle
);
404 #endif // defined(OS_POSIX) && !defined(OS_NACL)
406 case MessageAttachment::TYPE_MOJO_HANDLE
: {
407 mojo::ScopedHandle handle
=
408 static_cast<IPC::internal::MojoHandleAttachment
*>(
409 attachment
.get())->TakeHandle();
410 handles
->push_back(handle
.release().value());
418 return MOJO_RESULT_OK
;
422 MojoResult
ChannelMojo::WriteToMessageAttachmentSet(
423 const std::vector
<MojoHandle
>& handle_buffer
,
425 for (size_t i
= 0; i
< handle_buffer
.size(); ++i
) {
426 bool ok
= message
->attachment_set()->AddAttachment(
427 new IPC::internal::MojoHandleAttachment(
428 mojo::MakeScopedHandle(mojo::Handle(handle_buffer
[i
]))));
431 LOG(ERROR
) << "Failed to add new Mojo handle.";
432 return MOJO_RESULT_UNKNOWN
;
436 return MOJO_RESULT_OK
;