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.
5 #include "ipc/ipc_channel_nacl.h"
13 #include "base/bind.h"
14 #include "base/logging.h"
15 #include "base/message_loop/message_loop_proxy.h"
16 #include "base/process_util.h"
17 #include "base/synchronization/lock.h"
18 #include "base/task_runner_util.h"
19 #include "base/threading/simple_thread.h"
20 #include "ipc/file_descriptor_set_posix.h"
21 #include "ipc/ipc_logging.h"
22 #include "native_client/src/public/imc_syscalls.h"
23 #include "native_client/src/public/imc_types.h"
27 struct MessageContents
{
28 std::vector
<char> data
;
34 bool ReadDataOnReaderThread(int pipe
, MessageContents
* contents
) {
39 contents
->data
.resize(Channel::kReadBufferSize
);
40 contents
->fds
.resize(FileDescriptorSet::kMaxDescriptorsPerMessage
);
42 NaClAbiNaClImcMsgIoVec iov
= { &contents
->data
[0], contents
->data
.size() };
43 NaClAbiNaClImcMsgHdr msg
= {
44 &iov
, 1, &contents
->fds
[0], contents
->fds
.size()
47 int bytes_read
= imc_recvmsg(pipe
, &msg
, 0);
49 if (bytes_read
<= 0) {
50 // NaClIPCAdapter::BlockingReceive returns -1 when the pipe closes (either
51 // due to error or for regular shutdown).
52 contents
->data
.clear();
53 contents
->fds
.clear();
57 // Resize the buffers down to the number of bytes and fds we actually read.
58 contents
->data
.resize(bytes_read
);
59 contents
->fds
.resize(msg
.desc_length
);
65 class Channel::ChannelImpl::ReaderThreadRunner
66 : public base::DelegateSimpleThread::Delegate
{
68 // |pipe|: A file descriptor from which we will read using imc_recvmsg.
69 // |data_read_callback|: A callback we invoke (on the main thread) when we
71 // |failure_callback|: A callback we invoke when we have a failure reading
73 // |main_message_loop|: A proxy for the main thread, where we will invoke the
77 base::Callback
<void (scoped_ptr
<MessageContents
>)> data_read_callback
,
78 base::Callback
<void ()> failure_callback
,
79 scoped_refptr
<base::MessageLoopProxy
> main_message_loop
);
81 // DelegateSimpleThread implementation. Reads data from the pipe in a loop
82 // until either we are told to quit or a read fails.
83 virtual void Run() OVERRIDE
;
87 base::Callback
<void (scoped_ptr
<MessageContents
>)> data_read_callback_
;
88 base::Callback
<void ()> failure_callback_
;
89 scoped_refptr
<base::MessageLoopProxy
> main_message_loop_
;
91 DISALLOW_COPY_AND_ASSIGN(ReaderThreadRunner
);
94 Channel::ChannelImpl::ReaderThreadRunner::ReaderThreadRunner(
96 base::Callback
<void (scoped_ptr
<MessageContents
>)> data_read_callback
,
97 base::Callback
<void ()> failure_callback
,
98 scoped_refptr
<base::MessageLoopProxy
> main_message_loop
)
100 data_read_callback_(data_read_callback
),
101 failure_callback_(failure_callback
),
102 main_message_loop_(main_message_loop
) {
105 void Channel::ChannelImpl::ReaderThreadRunner::Run() {
107 scoped_ptr
<MessageContents
> msg_contents(new MessageContents
);
108 bool success
= ReadDataOnReaderThread(pipe_
, msg_contents
.get());
110 main_message_loop_
->PostTask(FROM_HERE
,
111 base::Bind(data_read_callback_
, base::Passed(&msg_contents
)));
113 main_message_loop_
->PostTask(FROM_HERE
, failure_callback_
);
114 // Because the read failed, we know we're going to quit. Don't bother
115 // trying to read again.
121 Channel::ChannelImpl::ChannelImpl(const IPC::ChannelHandle
& channel_handle
,
124 : ChannelReader(listener
),
126 waiting_connect_(true),
128 pipe_name_(channel_handle
.name
),
129 weak_ptr_factory_(this) {
130 if (!CreatePipe(channel_handle
)) {
131 // The pipe may have been closed already.
132 const char *modestr
= (mode_
& MODE_SERVER_FLAG
) ? "server" : "client";
133 LOG(WARNING
) << "Unable to create pipe named \"" << channel_handle
.name
134 << "\" in " << modestr
<< " mode";
138 Channel::ChannelImpl::~ChannelImpl() {
142 bool Channel::ChannelImpl::Connect() {
144 DLOG(INFO
) << "Channel creation failed: " << pipe_name_
;
148 // Note that Connect is called on the "Channel" thread (i.e., the same thread
149 // where Channel::Send will be called, and the same thread that should receive
150 // messages). The constructor might be invoked on another thread (see
151 // ChannelProxy for an example of that). Therefore, we must wait until Connect
152 // is called to decide which MessageLoopProxy to pass to ReaderThreadRunner.
153 reader_thread_runner_
.reset(
154 new ReaderThreadRunner(
156 base::Bind(&Channel::ChannelImpl::DidRecvMsg
,
157 weak_ptr_factory_
.GetWeakPtr()),
158 base::Bind(&Channel::ChannelImpl::ReadDidFail
,
159 weak_ptr_factory_
.GetWeakPtr()),
160 base::MessageLoopProxy::current()));
161 reader_thread_
.reset(
162 new base::DelegateSimpleThread(reader_thread_runner_
.get(),
163 "ipc_channel_nacl reader thread"));
164 reader_thread_
->Start();
165 waiting_connect_
= false;
166 // If there were any messages queued before connection, send them.
167 ProcessOutgoingMessages();
171 void Channel::ChannelImpl::Close() {
172 // For now, we assume that at shutdown, the reader thread will be woken with
173 // a failure (see NaClIPCAdapter::BlockingRead and CloseChannel). Or... we
174 // might simply be killed with no chance to clean up anyway :-).
175 // If untrusted code tries to close the channel prior to shutdown, it's likely
177 // TODO(dmichael): Can we do anything smarter here to make sure the reader
178 // thread wakes up and quits?
179 reader_thread_
->Join();
182 reader_thread_runner_
.reset();
183 reader_thread_
.reset();
185 output_queue_
.clear();
188 bool Channel::ChannelImpl::Send(Message
* message
) {
189 DVLOG(2) << "sending message @" << message
<< " on channel @" << this
190 << " with type " << message
->type();
191 scoped_ptr
<Message
> message_ptr(message
);
193 #ifdef IPC_MESSAGE_LOG_ENABLED
194 Logging::GetInstance()->OnSendMessage(message_ptr
.get(), "");
195 #endif // IPC_MESSAGE_LOG_ENABLED
197 message
->TraceMessageBegin();
198 output_queue_
.push_back(linked_ptr
<Message
>(message_ptr
.release()));
199 if (!waiting_connect_
)
200 return ProcessOutgoingMessages();
205 void Channel::ChannelImpl::DidRecvMsg(scoped_ptr
<MessageContents
> contents
) {
206 // Close sets the pipe to -1. It's possible we'll get a buffer sent to us from
207 // the reader thread after Close is called. If so, we ignore it.
211 linked_ptr
<std::vector
<char> > data(new std::vector
<char>);
212 data
->swap(contents
->data
);
213 read_queue_
.push_back(data
);
215 input_fds_
.insert(input_fds_
.end(),
216 contents
->fds
.begin(), contents
->fds
.end());
217 contents
->fds
.clear();
219 // In POSIX, we would be told when there are bytes to read by implementing
220 // OnFileCanReadWithoutBlocking in MessageLoopForIO::Watcher. In NaCl, we
221 // instead know at this point because the reader thread posted some data to
223 ProcessIncomingMessages();
226 void Channel::ChannelImpl::ReadDidFail() {
230 bool Channel::ChannelImpl::CreatePipe(
231 const IPC::ChannelHandle
& channel_handle
) {
234 // There's one possible case in NaCl:
235 // 1) It's a channel wrapping a pipe that is given to us.
236 // We don't support these:
237 // 2) It's for a named channel.
238 // 3) It's for a client that we implement ourself.
239 // 4) It's the initial IPC channel.
241 if (channel_handle
.socket
.fd
== -1) {
245 pipe_
= channel_handle
.socket
.fd
;
249 bool Channel::ChannelImpl::ProcessOutgoingMessages() {
250 DCHECK(!waiting_connect_
); // Why are we trying to send messages if there's
252 if (output_queue_
.empty())
258 // Write out all the messages. The trusted implementation is guaranteed to not
259 // block. See NaClIPCAdapter::Send for the implementation of imc_sendmsg.
260 while (!output_queue_
.empty()) {
261 linked_ptr
<Message
> msg
= output_queue_
.front();
262 output_queue_
.pop_front();
264 int fds
[FileDescriptorSet::kMaxDescriptorsPerMessage
];
265 const size_t num_fds
= msg
->file_descriptor_set()->size();
266 DCHECK(num_fds
<= FileDescriptorSet::kMaxDescriptorsPerMessage
);
267 msg
->file_descriptor_set()->GetDescriptors(fds
);
269 NaClAbiNaClImcMsgIoVec iov
= {
270 const_cast<void*>(msg
->data()), msg
->size()
272 NaClAbiNaClImcMsgHdr msgh
= { &iov
, 1, fds
, num_fds
};
273 ssize_t bytes_written
= imc_sendmsg(pipe_
, &msgh
, 0);
275 DCHECK(bytes_written
); // The trusted side shouldn't return 0.
276 if (bytes_written
< 0) {
277 // The trusted side should only ever give us an error of EPIPE. We
278 // should never be interrupted, nor should we get EAGAIN.
279 DCHECK(errno
== EPIPE
);
281 PLOG(ERROR
) << "pipe_ error on "
283 << " Currently writing message of size: "
287 msg
->file_descriptor_set()->CommitAll();
291 DVLOG(2) << "sent message @" << msg
.get() << " with type " << msg
->type()
292 << " on fd " << pipe_
;
297 Channel::ChannelImpl::ReadState
Channel::ChannelImpl::ReadData(
304 if (read_queue_
.empty())
306 while (!read_queue_
.empty() && *bytes_read
< buffer_len
) {
307 linked_ptr
<std::vector
<char> > vec(read_queue_
.front());
308 size_t bytes_to_read
= buffer_len
- *bytes_read
;
309 if (vec
->size() <= bytes_to_read
) {
310 // We can read and discard the entire vector.
311 std::copy(vec
->begin(), vec
->end(), buffer
+ *bytes_read
);
312 *bytes_read
+= vec
->size();
313 read_queue_
.pop_front();
315 // Read all the bytes we can and discard them from the front of the
316 // vector. (This can be slowish, since erase has to move the back of the
317 // vector to the front, but it's hopefully a temporary hack and it keeps
319 std::copy(vec
->begin(), vec
->begin() + bytes_to_read
,
320 buffer
+ *bytes_read
);
321 vec
->erase(vec
->begin(), vec
->begin() + bytes_to_read
);
322 *bytes_read
+= bytes_to_read
;
325 return READ_SUCCEEDED
;
328 bool Channel::ChannelImpl::WillDispatchInputMessage(Message
* msg
) {
329 uint16 header_fds
= msg
->header()->num_fds
;
330 CHECK(header_fds
== input_fds_
.size());
332 return true; // Nothing to do.
334 // The shenaniganery below with &foo.front() requires input_fds_ to have
335 // contiguous underlying storage (such as a simple array or a std::vector).
336 // This is why the header warns not to make input_fds_ a deque<>.
337 msg
->file_descriptor_set()->SetDescriptors(&input_fds_
.front(),
343 bool Channel::ChannelImpl::DidEmptyInputBuffers() {
344 // When the input data buffer is empty, the fds should be too.
345 return input_fds_
.empty();
348 void Channel::ChannelImpl::HandleHelloMessage(const Message
& msg
) {
349 // The trusted side IPC::Channel should handle the "hello" handshake; we
350 // should not receive the "Hello" message.
354 //------------------------------------------------------------------------------
355 // Channel's methods simply call through to ChannelImpl.
357 Channel::Channel(const IPC::ChannelHandle
& channel_handle
,
360 : channel_impl_(new ChannelImpl(channel_handle
, mode
, listener
)) {
363 Channel::~Channel() {
364 delete channel_impl_
;
367 bool Channel::Connect() {
368 return channel_impl_
->Connect();
371 void Channel::Close() {
372 channel_impl_
->Close();
375 base::ProcessId
Channel::peer_pid() const {
376 // This shouldn't actually get used in the untrusted side of the proxy, and we
377 // don't have the real pid anyway.
381 bool Channel::Send(Message
* message
) {
382 return channel_impl_
->Send(message
);