Revert of Enable Surfaces on Android (try #2) (patchset #1 id:1 of https://codereview...
[chromium-blink-merge.git] / ipc / mojo / ipc_channel_mojo.cc
blob1f3e3c44561b905eea3fa2752ec7c4d17ba11b70
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"
7 #include "base/bind.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 "mojo/edk/embedder/embedder.h"
17 #include "mojo/public/cpp/bindings/error_handler.h"
19 namespace IPC {
21 namespace {
23 class MojoChannelFactory : public ChannelFactory {
24 public:
25 MojoChannelFactory(ChannelMojo::Delegate* delegate,
26 ChannelHandle channel_handle,
27 Channel::Mode mode)
28 : delegate_(delegate), channel_handle_(channel_handle), mode_(mode) {}
30 std::string GetName() const override {
31 return channel_handle_.name;
34 scoped_ptr<Channel> BuildChannel(Listener* listener) override {
35 return ChannelMojo::Create(delegate_, channel_handle_, mode_, listener);
38 private:
39 ChannelMojo::Delegate* delegate_;
40 ChannelHandle channel_handle_;
41 Channel::Mode mode_;
44 //------------------------------------------------------------------------------
46 class ClientChannelMojo
47 : public ChannelMojo,
48 public NON_EXPORTED_BASE(mojo::InterfaceImpl<ClientChannel>) {
49 public:
50 ClientChannelMojo(ChannelMojo::Delegate* delegate,
51 const ChannelHandle& handle,
52 Listener* listener);
53 ~ClientChannelMojo() override;
54 // MojoBootstrap::Delegate implementation
55 void OnPipeAvailable(mojo::embedder::ScopedPlatformHandle handle) override;
56 // InterfaceImpl implementation
57 void OnConnectionError() override;
58 // ClientChannel implementation
59 void Init(
60 mojo::ScopedMessagePipeHandle pipe,
61 int32_t peer_pid,
62 const mojo::Callback<void(int32_t)>& callback) override;
64 DISALLOW_COPY_AND_ASSIGN(ClientChannelMojo);
67 ClientChannelMojo::ClientChannelMojo(ChannelMojo::Delegate* delegate,
68 const ChannelHandle& handle,
69 Listener* listener)
70 : ChannelMojo(delegate, handle, Channel::MODE_CLIENT, listener) {
73 ClientChannelMojo::~ClientChannelMojo() {
76 void ClientChannelMojo::OnPipeAvailable(
77 mojo::embedder::ScopedPlatformHandle handle) {
78 mojo::WeakBindToPipe(this, CreateMessagingPipe(handle.Pass()));
81 void ClientChannelMojo::OnConnectionError() {
82 listener()->OnChannelError();
85 void ClientChannelMojo::Init(
86 mojo::ScopedMessagePipeHandle pipe,
87 int32_t peer_pid,
88 const mojo::Callback<void(int32_t)>& callback) {
89 InitMessageReader(pipe.Pass(), static_cast<base::ProcessId>(peer_pid));
90 callback.Run(GetSelfPID());
93 //------------------------------------------------------------------------------
95 class ServerChannelMojo : public ChannelMojo, public mojo::ErrorHandler {
96 public:
97 ServerChannelMojo(ChannelMojo::Delegate* delegate,
98 const ChannelHandle& handle,
99 Listener* listener);
100 ~ServerChannelMojo() override;
102 // MojoBootstrap::Delegate implementation
103 void OnPipeAvailable(mojo::embedder::ScopedPlatformHandle handle) override;
104 // ErrorHandler implementation
105 void OnConnectionError() override;
106 // Channel override
107 void Close() override;
109 private:
110 // ClientChannelClient implementation
111 void ClientChannelWasInitialized(int32_t peer_pid);
113 mojo::InterfacePtr<ClientChannel> client_channel_;
114 mojo::ScopedMessagePipeHandle message_pipe_;
116 DISALLOW_COPY_AND_ASSIGN(ServerChannelMojo);
119 ServerChannelMojo::ServerChannelMojo(ChannelMojo::Delegate* delegate,
120 const ChannelHandle& handle,
121 Listener* listener)
122 : ChannelMojo(delegate, handle, Channel::MODE_SERVER, listener) {
125 ServerChannelMojo::~ServerChannelMojo() {
126 Close();
129 void ServerChannelMojo::OnPipeAvailable(
130 mojo::embedder::ScopedPlatformHandle handle) {
131 mojo::ScopedMessagePipeHandle peer;
132 MojoResult create_result =
133 mojo::CreateMessagePipe(nullptr, &message_pipe_, &peer);
134 if (create_result != MOJO_RESULT_OK) {
135 DLOG(WARNING) << "mojo::CreateMessagePipe failed: " << create_result;
136 listener()->OnChannelError();
137 return;
140 client_channel_.Bind(CreateMessagingPipe(handle.Pass()));
141 client_channel_.set_error_handler(this);
142 client_channel_->Init(
143 peer.Pass(),
144 static_cast<int32_t>(GetSelfPID()),
145 base::Bind(&ServerChannelMojo::ClientChannelWasInitialized,
146 base::Unretained(this)));
149 void ServerChannelMojo::ClientChannelWasInitialized(int32_t peer_pid) {
150 InitMessageReader(message_pipe_.Pass(), peer_pid);
153 void ServerChannelMojo::OnConnectionError() {
154 listener()->OnChannelError();
157 void ServerChannelMojo::Close() {
158 client_channel_.reset();
159 message_pipe_.reset();
160 ChannelMojo::Close();
163 } // namespace
165 //------------------------------------------------------------------------------
167 void ChannelMojo::ChannelInfoDeleter::operator()(
168 mojo::embedder::ChannelInfo* ptr) const {
169 mojo::embedder::DestroyChannel(ptr);
172 //------------------------------------------------------------------------------
174 // static
175 bool ChannelMojo::ShouldBeUsed() {
176 // TODO(morrita): Turn this on for a set of platforms.
177 return false;
180 // static
181 scoped_ptr<ChannelMojo> ChannelMojo::Create(ChannelMojo::Delegate* delegate,
182 const ChannelHandle& channel_handle,
183 Mode mode,
184 Listener* listener) {
185 switch (mode) {
186 case Channel::MODE_CLIENT:
187 return make_scoped_ptr(
188 new ClientChannelMojo(delegate, channel_handle, listener));
189 case Channel::MODE_SERVER:
190 return make_scoped_ptr(
191 new ServerChannelMojo(delegate, channel_handle, listener));
192 default:
193 NOTREACHED();
194 return nullptr;
198 // static
199 scoped_ptr<ChannelFactory> ChannelMojo::CreateServerFactory(
200 ChannelMojo::Delegate* delegate,
201 const ChannelHandle& channel_handle) {
202 return make_scoped_ptr(
203 new MojoChannelFactory(delegate, channel_handle, Channel::MODE_SERVER));
206 // static
207 scoped_ptr<ChannelFactory> ChannelMojo::CreateClientFactory(
208 const ChannelHandle& channel_handle) {
209 return make_scoped_ptr(
210 new MojoChannelFactory(NULL, channel_handle, Channel::MODE_CLIENT));
213 ChannelMojo::ChannelMojo(ChannelMojo::Delegate* delegate,
214 const ChannelHandle& handle,
215 Mode mode,
216 Listener* listener)
217 : mode_(mode),
218 listener_(listener),
219 peer_pid_(base::kNullProcessId),
220 weak_factory_(this) {
221 // Create MojoBootstrap after all members are set as it touches
222 // ChannelMojo from a different thread.
223 bootstrap_ = MojoBootstrap::Create(handle, mode, this);
224 if (delegate) {
225 if (delegate->GetIOTaskRunner() ==
226 base::MessageLoop::current()->message_loop_proxy()) {
227 InitDelegate(delegate);
228 } else {
229 delegate->GetIOTaskRunner()->PostTask(
230 FROM_HERE,
231 base::Bind(
232 &ChannelMojo::InitDelegate, base::Unretained(this), delegate));
237 ChannelMojo::~ChannelMojo() {
238 Close();
241 void ChannelMojo::InitDelegate(ChannelMojo::Delegate* delegate) {
242 delegate_ = delegate->ToWeakPtr();
243 delegate_->OnChannelCreated(weak_factory_.GetWeakPtr());
246 mojo::ScopedMessagePipeHandle ChannelMojo::CreateMessagingPipe(
247 mojo::embedder::ScopedPlatformHandle handle) {
248 DCHECK(!channel_info_.get());
249 mojo::embedder::ChannelInfo* channel_info;
250 mojo::ScopedMessagePipeHandle pipe =
251 mojo::embedder::CreateChannelOnIOThread(handle.Pass(), &channel_info);
252 channel_info_.reset(channel_info);
253 return pipe.Pass();
256 bool ChannelMojo::Connect() {
257 DCHECK(!message_reader_);
258 return bootstrap_->Connect();
261 void ChannelMojo::Close() {
262 message_reader_.reset();
263 channel_info_.reset();
266 void ChannelMojo::OnBootstrapError() {
267 listener_->OnChannelError();
270 void ChannelMojo::InitMessageReader(mojo::ScopedMessagePipeHandle pipe,
271 int32_t peer_pid) {
272 message_reader_ =
273 make_scoped_ptr(new internal::MessagePipeReader(pipe.Pass(), this));
275 for (size_t i = 0; i < pending_messages_.size(); ++i) {
276 bool sent = message_reader_->Send(make_scoped_ptr(pending_messages_[i]));
277 pending_messages_[i] = NULL;
278 if (!sent) {
279 pending_messages_.clear();
280 listener_->OnChannelError();
281 return;
285 pending_messages_.clear();
287 set_peer_pid(peer_pid);
288 listener_->OnChannelConnected(static_cast<int32_t>(GetPeerPID()));
289 if (message_reader_)
290 message_reader_->ReadMessagesThenWait();
293 void ChannelMojo::OnPipeClosed(internal::MessagePipeReader* reader) {
294 Close();
297 void ChannelMojo::OnPipeError(internal::MessagePipeReader* reader) {
298 listener_->OnChannelError();
302 bool ChannelMojo::Send(Message* message) {
303 if (!message_reader_) {
304 pending_messages_.push_back(message);
305 return true;
308 return message_reader_->Send(make_scoped_ptr(message));
311 base::ProcessId ChannelMojo::GetPeerPID() const {
312 return peer_pid_;
315 base::ProcessId ChannelMojo::GetSelfPID() const {
316 return base::GetCurrentProcId();
319 void ChannelMojo::OnClientLaunched(base::ProcessHandle handle) {
320 bootstrap_->OnClientLaunched(handle);
323 void ChannelMojo::OnMessageReceived(Message& message) {
324 TRACE_EVENT2("ipc,toplevel", "ChannelMojo::OnMessageReceived",
325 "class", IPC_MESSAGE_ID_CLASS(message.type()),
326 "line", IPC_MESSAGE_ID_LINE(message.type()));
327 listener_->OnMessageReceived(message);
328 if (message.dispatch_error())
329 listener_->OnBadMessageReceived(message);
332 #if defined(OS_POSIX) && !defined(OS_NACL)
333 int ChannelMojo::GetClientFileDescriptor() const {
334 return bootstrap_->GetClientFileDescriptor();
337 base::ScopedFD ChannelMojo::TakeClientFileDescriptor() {
338 return bootstrap_->TakeClientFileDescriptor();
341 // static
342 MojoResult ChannelMojo::WriteToMessageAttachmentSet(
343 const std::vector<MojoHandle>& handle_buffer,
344 Message* message) {
345 for (size_t i = 0; i < handle_buffer.size(); ++i) {
346 mojo::embedder::ScopedPlatformHandle platform_handle;
347 MojoResult unwrap_result = mojo::embedder::PassWrappedPlatformHandle(
348 handle_buffer[i], &platform_handle);
349 if (unwrap_result != MOJO_RESULT_OK) {
350 DLOG(WARNING) << "Pipe failed to covert handles. Closing: "
351 << unwrap_result;
352 return unwrap_result;
355 bool ok = message->attachment_set()->AddToOwn(
356 base::ScopedFD(platform_handle.release().fd));
357 DCHECK(ok);
360 return MOJO_RESULT_OK;
363 // static
364 MojoResult ChannelMojo::ReadFromMessageAttachmentSet(
365 Message* message,
366 std::vector<MojoHandle>* handles) {
367 // We dup() the handles in IPC::Message to transmit.
368 // IPC::MessageAttachmentSet has intricate lifecycle semantics
369 // of FDs, so just to dup()-and-own them is the safest option.
370 if (message->HasFileDescriptors()) {
371 MessageAttachmentSet* fdset = message->attachment_set();
372 std::vector<base::PlatformFile> fds_to_send(fdset->size());
373 fdset->PeekDescriptors(&fds_to_send[0]);
374 for (size_t i = 0; i < fds_to_send.size(); ++i) {
375 int fd_to_send = dup(fds_to_send[i]);
376 if (-1 == fd_to_send) {
377 DPLOG(WARNING) << "Failed to dup FD to transmit.";
378 fdset->CommitAll();
379 return MOJO_RESULT_UNKNOWN;
382 MojoHandle wrapped_handle;
383 MojoResult wrap_result = CreatePlatformHandleWrapper(
384 mojo::embedder::ScopedPlatformHandle(
385 mojo::embedder::PlatformHandle(fd_to_send)),
386 &wrapped_handle);
387 if (MOJO_RESULT_OK != wrap_result) {
388 DLOG(WARNING) << "Pipe failed to wrap handles. Closing: "
389 << wrap_result;
390 fdset->CommitAll();
391 return wrap_result;
394 handles->push_back(wrapped_handle);
397 fdset->CommitAll();
400 return MOJO_RESULT_OK;
403 #endif // defined(OS_POSIX) && !defined(OS_NACL)
405 } // namespace IPC