Update broken references to image assets
[chromium-blink-merge.git] / ipc / ipc_channel_nacl.cc
blob2e5f8b32fcd05bb2f87d0939f4c46c999bb295a1
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/single_thread_task_runner.h"
16 #include "base/synchronization/lock.h"
17 #include "base/task_runner_util.h"
18 #include "base/thread_task_runner_handle.h"
19 #include "base/threading/simple_thread.h"
20 #include "ipc/ipc_listener.h"
21 #include "ipc/ipc_logging.h"
22 #include "ipc/ipc_message_attachment_set.h"
23 #include "native_client/src/public/imc_syscalls.h"
24 #include "native_client/src/public/imc_types.h"
26 namespace IPC {
28 struct MessageContents {
29 std::vector<char> data;
30 std::vector<int> fds;
33 namespace {
35 bool ReadDataOnReaderThread(int pipe, MessageContents* contents) {
36 DCHECK(pipe >= 0);
37 if (pipe < 0)
38 return false;
40 contents->data.resize(Channel::kReadBufferSize);
41 contents->fds.resize(NACL_ABI_IMC_DESC_MAX);
43 NaClAbiNaClImcMsgIoVec iov = { &contents->data[0], contents->data.size() };
44 NaClAbiNaClImcMsgHdr msg = {
45 &iov, 1, &contents->fds[0], contents->fds.size()
48 int bytes_read = imc_recvmsg(pipe, &msg, 0);
50 if (bytes_read <= 0) {
51 // NaClIPCAdapter::BlockingReceive returns -1 when the pipe closes (either
52 // due to error or for regular shutdown).
53 contents->data.clear();
54 contents->fds.clear();
55 return false;
57 DCHECK(bytes_read);
58 // Resize the buffers down to the number of bytes and fds we actually read.
59 contents->data.resize(bytes_read);
60 contents->fds.resize(msg.desc_length);
61 return true;
64 } // namespace
66 class ChannelNacl::ReaderThreadRunner
67 : public base::DelegateSimpleThread::Delegate {
68 public:
69 // |pipe|: A file descriptor from which we will read using imc_recvmsg.
70 // |data_read_callback|: A callback we invoke (on the main thread) when we
71 // have read data.
72 // |failure_callback|: A callback we invoke when we have a failure reading
73 // from |pipe|.
74 // |main_message_loop|: A proxy for the main thread, where we will invoke the
75 // above callbacks.
76 ReaderThreadRunner(
77 int pipe,
78 base::Callback<void(scoped_ptr<MessageContents>)> data_read_callback,
79 base::Callback<void()> failure_callback,
80 scoped_refptr<base::SingleThreadTaskRunner> main_task_runner);
82 // DelegateSimpleThread implementation. Reads data from the pipe in a loop
83 // until either we are told to quit or a read fails.
84 void Run() override;
86 private:
87 int pipe_;
88 base::Callback<void (scoped_ptr<MessageContents>)> data_read_callback_;
89 base::Callback<void ()> failure_callback_;
90 scoped_refptr<base::SingleThreadTaskRunner> main_task_runner_;
92 DISALLOW_COPY_AND_ASSIGN(ReaderThreadRunner);
95 ChannelNacl::ReaderThreadRunner::ReaderThreadRunner(
96 int pipe,
97 base::Callback<void(scoped_ptr<MessageContents>)> data_read_callback,
98 base::Callback<void()> failure_callback,
99 scoped_refptr<base::SingleThreadTaskRunner> main_task_runner)
100 : pipe_(pipe),
101 data_read_callback_(data_read_callback),
102 failure_callback_(failure_callback),
103 main_task_runner_(main_task_runner) {
106 void ChannelNacl::ReaderThreadRunner::Run() {
107 while (true) {
108 scoped_ptr<MessageContents> msg_contents(new MessageContents);
109 bool success = ReadDataOnReaderThread(pipe_, msg_contents.get());
110 if (success) {
111 main_task_runner_->PostTask(
112 FROM_HERE,
113 base::Bind(data_read_callback_, base::Passed(&msg_contents)));
114 } else {
115 main_task_runner_->PostTask(FROM_HERE, failure_callback_);
116 // Because the read failed, we know we're going to quit. Don't bother
117 // trying to read again.
118 return;
123 ChannelNacl::ChannelNacl(const IPC::ChannelHandle& channel_handle,
124 Mode mode,
125 Listener* listener,
126 AttachmentBroker* broker)
127 : ChannelReader(listener),
128 mode_(mode),
129 waiting_connect_(true),
130 pipe_(-1),
131 pipe_name_(channel_handle.name),
132 weak_ptr_factory_(this),
133 broker_(broker) {
134 if (!CreatePipe(channel_handle)) {
135 // The pipe may have been closed already.
136 const char *modestr = (mode_ & MODE_SERVER_FLAG) ? "server" : "client";
137 LOG(WARNING) << "Unable to create pipe named \"" << channel_handle.name
138 << "\" in " << modestr << " mode";
142 ChannelNacl::~ChannelNacl() {
143 Close();
146 base::ProcessId ChannelNacl::GetPeerPID() const {
147 // This shouldn't actually get used in the untrusted side of the proxy, and we
148 // don't have the real pid anyway.
149 return -1;
152 base::ProcessId ChannelNacl::GetSelfPID() const {
153 return -1;
156 bool ChannelNacl::Connect() {
157 if (pipe_ == -1) {
158 DLOG(WARNING) << "Channel creation failed: " << pipe_name_;
159 return false;
162 // Note that Connect is called on the "Channel" thread (i.e., the same thread
163 // where Channel::Send will be called, and the same thread that should receive
164 // messages). The constructor might be invoked on another thread (see
165 // ChannelProxy for an example of that). Therefore, we must wait until Connect
166 // is called to decide which SingleThreadTaskRunner to pass to
167 // ReaderThreadRunner.
168 reader_thread_runner_.reset(new ReaderThreadRunner(
169 pipe_,
170 base::Bind(&ChannelNacl::DidRecvMsg, weak_ptr_factory_.GetWeakPtr()),
171 base::Bind(&ChannelNacl::ReadDidFail, weak_ptr_factory_.GetWeakPtr()),
172 base::ThreadTaskRunnerHandle::Get()));
173 reader_thread_.reset(
174 new base::DelegateSimpleThread(reader_thread_runner_.get(),
175 "ipc_channel_nacl reader thread"));
176 reader_thread_->Start();
177 waiting_connect_ = false;
178 // If there were any messages queued before connection, send them.
179 ProcessOutgoingMessages();
180 base::ThreadTaskRunnerHandle::Get()->PostTask(
181 FROM_HERE, base::Bind(&ChannelNacl::CallOnChannelConnected,
182 weak_ptr_factory_.GetWeakPtr()));
184 return true;
187 void ChannelNacl::Close() {
188 // For now, we assume that at shutdown, the reader thread will be woken with
189 // a failure (see NaClIPCAdapter::BlockingRead and CloseChannel). Or... we
190 // might simply be killed with no chance to clean up anyway :-).
191 // If untrusted code tries to close the channel prior to shutdown, it's likely
192 // to hang.
193 // TODO(dmichael): Can we do anything smarter here to make sure the reader
194 // thread wakes up and quits?
195 reader_thread_->Join();
196 close(pipe_);
197 pipe_ = -1;
198 reader_thread_runner_.reset();
199 reader_thread_.reset();
200 read_queue_.clear();
201 output_queue_.clear();
204 bool ChannelNacl::Send(Message* message) {
205 DCHECK(!message->HasAttachments());
206 DVLOG(2) << "sending message @" << message << " on channel @" << this
207 << " with type " << message->type();
208 scoped_ptr<Message> message_ptr(message);
210 #ifdef IPC_MESSAGE_LOG_ENABLED
211 Logging::GetInstance()->OnSendMessage(message_ptr.get(), "");
212 #endif // IPC_MESSAGE_LOG_ENABLED
214 TRACE_EVENT_WITH_FLOW0(TRACE_DISABLED_BY_DEFAULT("ipc.flow"),
215 "ChannelNacl::Send",
216 message->header()->flags,
217 TRACE_EVENT_FLAG_FLOW_OUT);
218 output_queue_.push_back(linked_ptr<Message>(message_ptr.release()));
219 if (!waiting_connect_)
220 return ProcessOutgoingMessages();
222 return true;
225 AttachmentBroker* ChannelNacl::GetAttachmentBroker() {
226 return broker_;
229 void ChannelNacl::DidRecvMsg(scoped_ptr<MessageContents> contents) {
230 // Close sets the pipe to -1. It's possible we'll get a buffer sent to us from
231 // the reader thread after Close is called. If so, we ignore it.
232 if (pipe_ == -1)
233 return;
235 linked_ptr<std::vector<char> > data(new std::vector<char>);
236 data->swap(contents->data);
237 read_queue_.push_back(data);
239 input_fds_.insert(input_fds_.end(),
240 contents->fds.begin(), contents->fds.end());
241 contents->fds.clear();
243 // In POSIX, we would be told when there are bytes to read by implementing
244 // OnFileCanReadWithoutBlocking in MessageLoopForIO::Watcher. In NaCl, we
245 // instead know at this point because the reader thread posted some data to
246 // us.
247 ProcessIncomingMessages();
250 void ChannelNacl::ReadDidFail() {
251 Close();
254 bool ChannelNacl::CreatePipe(
255 const IPC::ChannelHandle& channel_handle) {
256 DCHECK(pipe_ == -1);
258 // There's one possible case in NaCl:
259 // 1) It's a channel wrapping a pipe that is given to us.
260 // We don't support these:
261 // 2) It's for a named channel.
262 // 3) It's for a client that we implement ourself.
263 // 4) It's the initial IPC channel.
265 if (channel_handle.socket.fd == -1) {
266 NOTIMPLEMENTED();
267 return false;
269 pipe_ = channel_handle.socket.fd;
270 return true;
273 bool ChannelNacl::ProcessOutgoingMessages() {
274 DCHECK(!waiting_connect_); // Why are we trying to send messages if there's
275 // no connection?
276 if (output_queue_.empty())
277 return true;
279 if (pipe_ == -1)
280 return false;
282 // Write out all the messages. The trusted implementation is guaranteed to not
283 // block. See NaClIPCAdapter::Send for the implementation of imc_sendmsg.
284 while (!output_queue_.empty()) {
285 linked_ptr<Message> msg = output_queue_.front();
286 output_queue_.pop_front();
288 int fds[MessageAttachmentSet::kMaxDescriptorsPerMessage];
289 const size_t num_fds = msg->attachment_set()->size();
290 DCHECK(num_fds <= MessageAttachmentSet::kMaxDescriptorsPerMessage);
291 msg->attachment_set()->PeekDescriptors(fds);
293 NaClAbiNaClImcMsgIoVec iov = {
294 const_cast<void*>(msg->data()), msg->size()
296 NaClAbiNaClImcMsgHdr msgh = { &iov, 1, fds, num_fds };
297 ssize_t bytes_written = imc_sendmsg(pipe_, &msgh, 0);
299 DCHECK(bytes_written); // The trusted side shouldn't return 0.
300 if (bytes_written < 0) {
301 // The trusted side should only ever give us an error of EPIPE. We
302 // should never be interrupted, nor should we get EAGAIN.
303 DCHECK(errno == EPIPE);
304 Close();
305 PLOG(ERROR) << "pipe_ error on "
306 << pipe_
307 << " Currently writing message of size: "
308 << msg->size();
309 return false;
310 } else {
311 msg->attachment_set()->CommitAll();
314 // Message sent OK!
315 DVLOG(2) << "sent message @" << msg.get() << " with type " << msg->type()
316 << " on fd " << pipe_;
318 return true;
321 void ChannelNacl::CallOnChannelConnected() {
322 listener()->OnChannelConnected(GetPeerPID());
325 ChannelNacl::ReadState ChannelNacl::ReadData(
326 char* buffer,
327 int buffer_len,
328 int* bytes_read) {
329 *bytes_read = 0;
330 if (pipe_ == -1)
331 return READ_FAILED;
332 if (read_queue_.empty())
333 return READ_PENDING;
334 while (!read_queue_.empty() && *bytes_read < buffer_len) {
335 linked_ptr<std::vector<char> > vec(read_queue_.front());
336 size_t bytes_to_read = buffer_len - *bytes_read;
337 if (vec->size() <= bytes_to_read) {
338 // We can read and discard the entire vector.
339 std::copy(vec->begin(), vec->end(), buffer + *bytes_read);
340 *bytes_read += vec->size();
341 read_queue_.pop_front();
342 } else {
343 // Read all the bytes we can and discard them from the front of the
344 // vector. (This can be slowish, since erase has to move the back of the
345 // vector to the front, but it's hopefully a temporary hack and it keeps
346 // the code simple).
347 std::copy(vec->begin(), vec->begin() + bytes_to_read,
348 buffer + *bytes_read);
349 vec->erase(vec->begin(), vec->begin() + bytes_to_read);
350 *bytes_read += bytes_to_read;
353 return READ_SUCCEEDED;
356 bool ChannelNacl::ShouldDispatchInputMessage(Message* msg) {
357 return true;
360 bool ChannelNacl::GetNonBrokeredAttachments(Message* msg) {
361 uint16 header_fds = msg->header()->num_fds;
362 CHECK(header_fds == input_fds_.size());
363 if (header_fds == 0)
364 return true; // Nothing to do.
366 // The shenaniganery below with &foo.front() requires input_fds_ to have
367 // contiguous underlying storage (such as a simple array or a std::vector).
368 // This is why the header warns not to make input_fds_ a deque<>.
369 msg->attachment_set()->AddDescriptorsToOwn(&input_fds_.front(), header_fds);
370 input_fds_.clear();
371 return true;
374 bool ChannelNacl::DidEmptyInputBuffers() {
375 // When the input data buffer is empty, the fds should be too.
376 return input_fds_.empty();
379 void ChannelNacl::HandleInternalMessage(const Message& msg) {
380 // The trusted side IPC::Channel should handle the "hello" handshake; we
381 // should not receive the "Hello" message.
382 NOTREACHED();
385 base::ProcessId ChannelNacl::GetSenderPID() {
386 // The untrusted side of the IPC::Channel should never have to worry about
387 // sender's process id.
388 return base::kNullProcessId;
391 bool ChannelNacl::IsAttachmentBrokerEndpoint() {
392 return is_attachment_broker_endpoint();
395 // Channel's methods
397 // static
398 scoped_ptr<Channel> Channel::Create(const IPC::ChannelHandle& channel_handle,
399 Mode mode,
400 Listener* listener,
401 AttachmentBroker* broker) {
402 return scoped_ptr<Channel>(
403 new ChannelNacl(channel_handle, mode, listener, broker));
406 } // namespace IPC