Updating trunk VERSION from 2139.0 to 2140.0
[chromium-blink-merge.git] / ipc / ipc_channel_nacl.cc
blob704f7d88d4267023e18af0f7c5d71e57405198cb
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"
7 #include <errno.h>
8 #include <stddef.h>
9 #include <sys/types.h>
11 #include <algorithm>
13 #include "base/bind.h"
14 #include "base/logging.h"
15 #include "base/message_loop/message_loop_proxy.h"
16 #include "base/synchronization/lock.h"
17 #include "base/task_runner_util.h"
18 #include "base/threading/simple_thread.h"
19 #include "ipc/file_descriptor_set_posix.h"
20 #include "ipc/ipc_listener.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"
25 namespace IPC {
27 struct MessageContents {
28 std::vector<char> data;
29 std::vector<int> fds;
32 namespace {
34 bool ReadDataOnReaderThread(int pipe, MessageContents* contents) {
35 DCHECK(pipe >= 0);
36 if (pipe < 0)
37 return false;
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();
54 return false;
56 DCHECK(bytes_read);
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);
60 return true;
63 } // namespace
65 class ChannelNacl::ReaderThreadRunner
66 : public base::DelegateSimpleThread::Delegate {
67 public:
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
70 // have read data.
71 // |failure_callback|: A callback we invoke when we have a failure reading
72 // from |pipe|.
73 // |main_message_loop|: A proxy for the main thread, where we will invoke the
74 // above callbacks.
75 ReaderThreadRunner(
76 int pipe,
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;
85 private:
86 int pipe_;
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 ChannelNacl::ReaderThreadRunner::ReaderThreadRunner(
95 int pipe,
96 base::Callback<void (scoped_ptr<MessageContents>)> data_read_callback,
97 base::Callback<void ()> failure_callback,
98 scoped_refptr<base::MessageLoopProxy> main_message_loop)
99 : pipe_(pipe),
100 data_read_callback_(data_read_callback),
101 failure_callback_(failure_callback),
102 main_message_loop_(main_message_loop) {
105 void ChannelNacl::ReaderThreadRunner::Run() {
106 while (true) {
107 scoped_ptr<MessageContents> msg_contents(new MessageContents);
108 bool success = ReadDataOnReaderThread(pipe_, msg_contents.get());
109 if (success) {
110 main_message_loop_->PostTask(FROM_HERE,
111 base::Bind(data_read_callback_, base::Passed(&msg_contents)));
112 } else {
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.
116 return;
121 ChannelNacl::ChannelNacl(const IPC::ChannelHandle& channel_handle,
122 Mode mode,
123 Listener* listener)
124 : ChannelReader(listener),
125 mode_(mode),
126 waiting_connect_(true),
127 pipe_(-1),
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 ChannelNacl::~ChannelNacl() {
139 Close();
142 base::ProcessId ChannelNacl::GetPeerPID() const {
143 // This shouldn't actually get used in the untrusted side of the proxy, and we
144 // don't have the real pid anyway.
145 return -1;
148 base::ProcessId ChannelNacl::GetSelfPID() const {
149 return -1;
152 ChannelHandle ChannelNacl::TakePipeHandle() {
153 // NACL doesn't have any platform-level handles.
154 return ChannelHandle();
157 bool ChannelNacl::Connect() {
158 if (pipe_ == -1) {
159 DLOG(WARNING) << "Channel creation failed: " << pipe_name_;
160 return false;
163 // Note that Connect is called on the "Channel" thread (i.e., the same thread
164 // where Channel::Send will be called, and the same thread that should receive
165 // messages). The constructor might be invoked on another thread (see
166 // ChannelProxy for an example of that). Therefore, we must wait until Connect
167 // is called to decide which MessageLoopProxy to pass to ReaderThreadRunner.
168 reader_thread_runner_.reset(
169 new ReaderThreadRunner(
170 pipe_,
171 base::Bind(&ChannelNacl::DidRecvMsg,
172 weak_ptr_factory_.GetWeakPtr()),
173 base::Bind(&ChannelNacl::ReadDidFail,
174 weak_ptr_factory_.GetWeakPtr()),
175 base::MessageLoopProxy::current()));
176 reader_thread_.reset(
177 new base::DelegateSimpleThread(reader_thread_runner_.get(),
178 "ipc_channel_nacl reader thread"));
179 reader_thread_->Start();
180 waiting_connect_ = false;
181 // If there were any messages queued before connection, send them.
182 ProcessOutgoingMessages();
183 base::MessageLoopProxy::current()->PostTask(FROM_HERE,
184 base::Bind(&ChannelNacl::CallOnChannelConnected,
185 weak_ptr_factory_.GetWeakPtr()));
187 return true;
190 void ChannelNacl::Close() {
191 // For now, we assume that at shutdown, the reader thread will be woken with
192 // a failure (see NaClIPCAdapter::BlockingRead and CloseChannel). Or... we
193 // might simply be killed with no chance to clean up anyway :-).
194 // If untrusted code tries to close the channel prior to shutdown, it's likely
195 // to hang.
196 // TODO(dmichael): Can we do anything smarter here to make sure the reader
197 // thread wakes up and quits?
198 reader_thread_->Join();
199 close(pipe_);
200 pipe_ = -1;
201 reader_thread_runner_.reset();
202 reader_thread_.reset();
203 read_queue_.clear();
204 output_queue_.clear();
207 bool ChannelNacl::Send(Message* message) {
208 DVLOG(2) << "sending message @" << message << " on channel @" << this
209 << " with type " << message->type();
210 scoped_ptr<Message> message_ptr(message);
212 #ifdef IPC_MESSAGE_LOG_ENABLED
213 Logging::GetInstance()->OnSendMessage(message_ptr.get(), "");
214 #endif // IPC_MESSAGE_LOG_ENABLED
216 message->TraceMessageBegin();
217 output_queue_.push_back(linked_ptr<Message>(message_ptr.release()));
218 if (!waiting_connect_)
219 return ProcessOutgoingMessages();
221 return true;
224 void ChannelNacl::DidRecvMsg(scoped_ptr<MessageContents> contents) {
225 // Close sets the pipe to -1. It's possible we'll get a buffer sent to us from
226 // the reader thread after Close is called. If so, we ignore it.
227 if (pipe_ == -1)
228 return;
230 linked_ptr<std::vector<char> > data(new std::vector<char>);
231 data->swap(contents->data);
232 read_queue_.push_back(data);
234 input_fds_.insert(input_fds_.end(),
235 contents->fds.begin(), contents->fds.end());
236 contents->fds.clear();
238 // In POSIX, we would be told when there are bytes to read by implementing
239 // OnFileCanReadWithoutBlocking in MessageLoopForIO::Watcher. In NaCl, we
240 // instead know at this point because the reader thread posted some data to
241 // us.
242 ProcessIncomingMessages();
245 void ChannelNacl::ReadDidFail() {
246 Close();
249 bool ChannelNacl::CreatePipe(
250 const IPC::ChannelHandle& channel_handle) {
251 DCHECK(pipe_ == -1);
253 // There's one possible case in NaCl:
254 // 1) It's a channel wrapping a pipe that is given to us.
255 // We don't support these:
256 // 2) It's for a named channel.
257 // 3) It's for a client that we implement ourself.
258 // 4) It's the initial IPC channel.
260 if (channel_handle.socket.fd == -1) {
261 NOTIMPLEMENTED();
262 return false;
264 pipe_ = channel_handle.socket.fd;
265 return true;
268 bool ChannelNacl::ProcessOutgoingMessages() {
269 DCHECK(!waiting_connect_); // Why are we trying to send messages if there's
270 // no connection?
271 if (output_queue_.empty())
272 return true;
274 if (pipe_ == -1)
275 return false;
277 // Write out all the messages. The trusted implementation is guaranteed to not
278 // block. See NaClIPCAdapter::Send for the implementation of imc_sendmsg.
279 while (!output_queue_.empty()) {
280 linked_ptr<Message> msg = output_queue_.front();
281 output_queue_.pop_front();
283 int fds[FileDescriptorSet::kMaxDescriptorsPerMessage];
284 const size_t num_fds = msg->file_descriptor_set()->size();
285 DCHECK(num_fds <= FileDescriptorSet::kMaxDescriptorsPerMessage);
286 msg->file_descriptor_set()->GetDescriptors(fds);
288 NaClAbiNaClImcMsgIoVec iov = {
289 const_cast<void*>(msg->data()), msg->size()
291 NaClAbiNaClImcMsgHdr msgh = { &iov, 1, fds, num_fds };
292 ssize_t bytes_written = imc_sendmsg(pipe_, &msgh, 0);
294 DCHECK(bytes_written); // The trusted side shouldn't return 0.
295 if (bytes_written < 0) {
296 // The trusted side should only ever give us an error of EPIPE. We
297 // should never be interrupted, nor should we get EAGAIN.
298 DCHECK(errno == EPIPE);
299 Close();
300 PLOG(ERROR) << "pipe_ error on "
301 << pipe_
302 << " Currently writing message of size: "
303 << msg->size();
304 return false;
305 } else {
306 msg->file_descriptor_set()->CommitAll();
309 // Message sent OK!
310 DVLOG(2) << "sent message @" << msg.get() << " with type " << msg->type()
311 << " on fd " << pipe_;
313 return true;
316 void ChannelNacl::CallOnChannelConnected() {
317 listener()->OnChannelConnected(GetPeerPID());
320 ChannelNacl::ReadState ChannelNacl::ReadData(
321 char* buffer,
322 int buffer_len,
323 int* bytes_read) {
324 *bytes_read = 0;
325 if (pipe_ == -1)
326 return READ_FAILED;
327 if (read_queue_.empty())
328 return READ_PENDING;
329 while (!read_queue_.empty() && *bytes_read < buffer_len) {
330 linked_ptr<std::vector<char> > vec(read_queue_.front());
331 size_t bytes_to_read = buffer_len - *bytes_read;
332 if (vec->size() <= bytes_to_read) {
333 // We can read and discard the entire vector.
334 std::copy(vec->begin(), vec->end(), buffer + *bytes_read);
335 *bytes_read += vec->size();
336 read_queue_.pop_front();
337 } else {
338 // Read all the bytes we can and discard them from the front of the
339 // vector. (This can be slowish, since erase has to move the back of the
340 // vector to the front, but it's hopefully a temporary hack and it keeps
341 // the code simple).
342 std::copy(vec->begin(), vec->begin() + bytes_to_read,
343 buffer + *bytes_read);
344 vec->erase(vec->begin(), vec->begin() + bytes_to_read);
345 *bytes_read += bytes_to_read;
348 return READ_SUCCEEDED;
351 bool ChannelNacl::WillDispatchInputMessage(Message* msg) {
352 uint16 header_fds = msg->header()->num_fds;
353 CHECK(header_fds == input_fds_.size());
354 if (header_fds == 0)
355 return true; // Nothing to do.
357 // The shenaniganery below with &foo.front() requires input_fds_ to have
358 // contiguous underlying storage (such as a simple array or a std::vector).
359 // This is why the header warns not to make input_fds_ a deque<>.
360 msg->file_descriptor_set()->SetDescriptors(&input_fds_.front(),
361 header_fds);
362 input_fds_.clear();
363 return true;
366 bool ChannelNacl::DidEmptyInputBuffers() {
367 // When the input data buffer is empty, the fds should be too.
368 return input_fds_.empty();
371 void ChannelNacl::HandleInternalMessage(const Message& msg) {
372 // The trusted side IPC::Channel should handle the "hello" handshake; we
373 // should not receive the "Hello" message.
374 NOTREACHED();
377 // Channel's methods
379 // static
380 scoped_ptr<Channel> Channel::Create(
381 const IPC::ChannelHandle &channel_handle, Mode mode, Listener* listener) {
382 return scoped_ptr<Channel>(
383 new ChannelNacl(channel_handle, mode, listener));
386 } // namespace IPC