Merge Chromium + Blink git repositories
[chromium-blink-merge.git] / components / nacl / loader / nacl_ipc_adapter.cc
blobf0b765874c987143f5a6fd0151dbf48144350544
1 // Copyright 2013 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 "components/nacl/loader/nacl_ipc_adapter.h"
7 #include <limits.h>
8 #include <string.h>
10 #include "base/basictypes.h"
11 #include "base/bind.h"
12 #include "base/location.h"
13 #include "base/memory/scoped_ptr.h"
14 #include "base/memory/shared_memory.h"
15 #include "base/task_runner_util.h"
16 #include "base/tuple.h"
17 #include "build/build_config.h"
18 #include "ipc/ipc_channel.h"
19 #include "ipc/ipc_platform_file.h"
20 #include "native_client/src/public/nacl_desc.h"
21 #include "native_client/src/public/nacl_desc_custom.h"
22 #include "native_client/src/trusted/desc/nacl_desc_quota.h"
23 #include "native_client/src/trusted/desc/nacl_desc_quota_interface.h"
24 #include "native_client/src/trusted/service_runtime/include/sys/fcntl.h"
25 #include "ppapi/c/ppb_file_io.h"
26 #include "ppapi/proxy/ppapi_messages.h"
27 #include "ppapi/proxy/serialized_handle.h"
29 using ppapi::proxy::NaClMessageScanner;
31 namespace {
33 enum BufferSizeStatus {
34 // The buffer contains a full message with no extra bytes.
35 MESSAGE_IS_COMPLETE,
37 // The message doesn't fit and the buffer contains only some of it.
38 MESSAGE_IS_TRUNCATED,
40 // The buffer contains a full message + extra data.
41 MESSAGE_HAS_EXTRA_DATA
44 BufferSizeStatus GetBufferStatus(const char* data, size_t len) {
45 if (len < sizeof(NaClIPCAdapter::NaClMessageHeader))
46 return MESSAGE_IS_TRUNCATED;
48 const NaClIPCAdapter::NaClMessageHeader* header =
49 reinterpret_cast<const NaClIPCAdapter::NaClMessageHeader*>(data);
50 uint32 message_size =
51 sizeof(NaClIPCAdapter::NaClMessageHeader) + header->payload_size;
53 if (len == message_size)
54 return MESSAGE_IS_COMPLETE;
55 if (len > message_size)
56 return MESSAGE_HAS_EXTRA_DATA;
57 return MESSAGE_IS_TRUNCATED;
60 //------------------------------------------------------------------------------
61 // This object allows the NaClDesc to hold a reference to a NaClIPCAdapter and
62 // forward calls to it.
63 struct DescThunker {
64 explicit DescThunker(NaClIPCAdapter* adapter_arg)
65 : adapter(adapter_arg) {
67 scoped_refptr<NaClIPCAdapter> adapter;
70 NaClIPCAdapter* ToAdapter(void* handle) {
71 return static_cast<DescThunker*>(handle)->adapter.get();
74 // NaClDescCustom implementation.
75 void NaClDescCustomDestroy(void* handle) {
76 delete static_cast<DescThunker*>(handle);
79 ssize_t NaClDescCustomSendMsg(void* handle, const NaClImcTypedMsgHdr* msg,
80 int /* flags */) {
81 return static_cast<ssize_t>(ToAdapter(handle)->Send(msg));
84 ssize_t NaClDescCustomRecvMsg(void* handle, NaClImcTypedMsgHdr* msg,
85 int /* flags */) {
86 return static_cast<ssize_t>(ToAdapter(handle)->BlockingReceive(msg));
89 NaClDesc* MakeNaClDescCustom(NaClIPCAdapter* adapter) {
90 NaClDescCustomFuncs funcs = NACL_DESC_CUSTOM_FUNCS_INITIALIZER;
91 funcs.Destroy = NaClDescCustomDestroy;
92 funcs.SendMsg = NaClDescCustomSendMsg;
93 funcs.RecvMsg = NaClDescCustomRecvMsg;
94 // NaClDescMakeCustomDesc gives us a reference on the returned NaClDesc.
95 return NaClDescMakeCustomDesc(new DescThunker(adapter), &funcs);
98 //------------------------------------------------------------------------------
99 // This object is passed to a NaClDescQuota to intercept writes and forward them
100 // to the NaClIPCAdapter, which checks quota. This is a NaCl-style struct. Don't
101 // add non-trivial fields or virtual methods. Construction should use malloc,
102 // because this is owned by the NaClDesc, and the NaCl Dtor code will call free.
103 struct QuotaInterface {
104 // The "base" struct must be first. NaCl code expects a NaCl style ref-counted
105 // object, so the "vtable" and other base class fields must be first.
106 struct NaClDescQuotaInterface base NACL_IS_REFCOUNT_SUBCLASS;
108 NaClMessageScanner::FileIO* file_io;
111 static void QuotaInterfaceDtor(NaClRefCount* nrcp) {
112 // Trivial class, just pass through to the "base" struct Dtor.
113 nrcp->vtbl = reinterpret_cast<NaClRefCountVtbl*>(
114 const_cast<NaClDescQuotaInterfaceVtbl*>(&kNaClDescQuotaInterfaceVtbl));
115 (*nrcp->vtbl->Dtor)(nrcp);
118 static int64_t QuotaInterfaceWriteRequest(NaClDescQuotaInterface* ndqi,
119 const uint8_t* /* unused_id */,
120 int64_t offset,
121 int64_t length) {
122 if (offset < 0 || length < 0)
123 return 0;
124 if (std::numeric_limits<int64_t>::max() - length < offset)
125 return 0; // offset + length would overflow.
126 int64_t max_offset = offset + length;
127 if (max_offset < 0)
128 return 0;
130 QuotaInterface* quota_interface = reinterpret_cast<QuotaInterface*>(ndqi);
131 NaClMessageScanner::FileIO* file_io = quota_interface->file_io;
132 int64_t increase = max_offset - file_io->max_written_offset();
133 if (increase <= 0 || file_io->Grow(increase))
134 return length;
136 return 0;
139 static int64_t QuotaInterfaceFtruncateRequest(NaClDescQuotaInterface* ndqi,
140 const uint8_t* /* unused_id */,
141 int64_t length) {
142 // We can't implement SetLength on the plugin side due to sandbox limitations.
143 // See crbug.com/156077.
144 NOTREACHED();
145 return 0;
148 static const struct NaClDescQuotaInterfaceVtbl kQuotaInterfaceVtbl = {
150 QuotaInterfaceDtor
152 QuotaInterfaceWriteRequest,
153 QuotaInterfaceFtruncateRequest
156 NaClDesc* MakeNaClDescQuota(
157 NaClMessageScanner::FileIO* file_io,
158 NaClDesc* wrapped_desc) {
159 // Create the QuotaInterface.
160 QuotaInterface* quota_interface =
161 static_cast<QuotaInterface*>(malloc(sizeof *quota_interface));
162 if (quota_interface && NaClDescQuotaInterfaceCtor(&quota_interface->base)) {
163 quota_interface->base.base.vtbl =
164 (struct NaClRefCountVtbl *)(&kQuotaInterfaceVtbl);
165 // QuotaInterface is a trivial class, so skip the ctor.
166 quota_interface->file_io = file_io;
167 // Create the NaClDescQuota.
168 NaClDescQuota* desc = static_cast<NaClDescQuota*>(malloc(sizeof *desc));
169 uint8_t unused_id[NACL_DESC_QUOTA_FILE_ID_LEN] = {0};
170 if (desc && NaClDescQuotaCtor(desc,
171 wrapped_desc,
172 unused_id,
173 &quota_interface->base)) {
174 return &desc->base;
176 if (desc)
177 NaClDescUnref(reinterpret_cast<NaClDesc*>(desc));
180 if (quota_interface)
181 NaClDescQuotaInterfaceUnref(&quota_interface->base);
183 return NULL;
186 //------------------------------------------------------------------------------
188 void DeleteChannel(IPC::Channel* channel) {
189 delete channel;
192 // Translates Pepper's read/write open flags into the NaCl equivalents.
193 // Since the host has already opened the file, flags such as O_CREAT, O_TRUNC,
194 // and O_EXCL don't make sense, so we filter those out. If no read or write
195 // flags are set, the function returns NACL_ABI_O_RDONLY as a safe fallback.
196 int TranslatePepperFileReadWriteOpenFlags(int32_t pp_open_flags) {
197 bool read = (pp_open_flags & PP_FILEOPENFLAG_READ) != 0;
198 bool write = (pp_open_flags & PP_FILEOPENFLAG_WRITE) != 0;
199 bool append = (pp_open_flags & PP_FILEOPENFLAG_APPEND) != 0;
201 int nacl_open_flag = NACL_ABI_O_RDONLY; // NACL_ABI_O_RDONLY == 0.
202 if (read && (write || append)) {
203 nacl_open_flag = NACL_ABI_O_RDWR;
204 } else if (write || append) {
205 nacl_open_flag = NACL_ABI_O_WRONLY;
206 } else if (!read) {
207 DLOG(WARNING) << "One of PP_FILEOPENFLAG_READ, PP_FILEOPENFLAG_WRITE, "
208 << "or PP_FILEOPENFLAG_APPEND should be set.";
210 if (append)
211 nacl_open_flag |= NACL_ABI_O_APPEND;
213 return nacl_open_flag;
216 class NaClDescWrapper {
217 public:
218 explicit NaClDescWrapper(NaClDesc* desc): desc_(desc) {}
219 ~NaClDescWrapper() {
220 NaClDescUnref(desc_);
223 NaClDesc* desc() { return desc_; }
225 private:
226 NaClDesc* desc_;
227 DISALLOW_COPY_AND_ASSIGN(NaClDescWrapper);
230 } // namespace
232 class NaClIPCAdapter::RewrittenMessage
233 : public base::RefCounted<RewrittenMessage> {
234 public:
235 RewrittenMessage();
237 bool is_consumed() const { return data_read_cursor_ == data_len_; }
239 void SetData(const NaClIPCAdapter::NaClMessageHeader& header,
240 const void* payload, size_t payload_length);
242 int Read(NaClImcTypedMsgHdr* msg);
244 void AddDescriptor(NaClDescWrapper* desc) { descs_.push_back(desc); }
246 size_t desc_count() const { return descs_.size(); }
248 private:
249 friend class base::RefCounted<RewrittenMessage>;
250 ~RewrittenMessage() {}
252 scoped_ptr<char[]> data_;
253 size_t data_len_;
255 // Offset into data where the next read will happen. This will be equal to
256 // data_len_ when all data has been consumed.
257 size_t data_read_cursor_;
259 // Wrapped descriptors for transfer to untrusted code.
260 ScopedVector<NaClDescWrapper> descs_;
263 NaClIPCAdapter::RewrittenMessage::RewrittenMessage()
264 : data_len_(0),
265 data_read_cursor_(0) {
268 void NaClIPCAdapter::RewrittenMessage::SetData(
269 const NaClIPCAdapter::NaClMessageHeader& header,
270 const void* payload,
271 size_t payload_length) {
272 DCHECK(!data_.get() && data_len_ == 0);
273 size_t header_len = sizeof(NaClIPCAdapter::NaClMessageHeader);
274 data_len_ = header_len + payload_length;
275 data_.reset(new char[data_len_]);
277 memcpy(data_.get(), &header, sizeof(NaClIPCAdapter::NaClMessageHeader));
278 memcpy(&data_[header_len], payload, payload_length);
281 int NaClIPCAdapter::RewrittenMessage::Read(NaClImcTypedMsgHdr* msg) {
282 CHECK(data_len_ >= data_read_cursor_);
283 char* dest_buffer = static_cast<char*>(msg->iov[0].base);
284 size_t dest_buffer_size = msg->iov[0].length;
285 size_t bytes_to_write = std::min(dest_buffer_size,
286 data_len_ - data_read_cursor_);
287 if (bytes_to_write == 0)
288 return 0;
290 memcpy(dest_buffer, &data_[data_read_cursor_], bytes_to_write);
291 data_read_cursor_ += bytes_to_write;
293 // Once all data has been consumed, transfer any file descriptors.
294 if (is_consumed()) {
295 nacl_abi_size_t desc_count = static_cast<nacl_abi_size_t>(descs_.size());
296 CHECK(desc_count <= msg->ndesc_length);
297 msg->ndesc_length = desc_count;
298 for (nacl_abi_size_t i = 0; i < desc_count; i++) {
299 // Copy the NaClDesc to the buffer and add a ref so it won't be freed
300 // when we clear our ScopedVector.
301 msg->ndescv[i] = descs_[i]->desc();
302 NaClDescRef(descs_[i]->desc());
304 descs_.clear();
305 } else {
306 msg->ndesc_length = 0;
308 return static_cast<int>(bytes_to_write);
311 NaClIPCAdapter::LockedData::LockedData()
312 : channel_closed_(false) {
315 NaClIPCAdapter::LockedData::~LockedData() {
318 NaClIPCAdapter::IOThreadData::IOThreadData() {
321 NaClIPCAdapter::IOThreadData::~IOThreadData() {
324 NaClIPCAdapter::NaClIPCAdapter(const IPC::ChannelHandle& handle,
325 base::TaskRunner* runner,
326 ResolveFileTokenCallback resolve_file_token_cb,
327 OpenResourceCallback open_resource_cb)
328 : lock_(),
329 cond_var_(&lock_),
330 task_runner_(runner),
331 resolve_file_token_cb_(resolve_file_token_cb),
332 open_resource_cb_(open_resource_cb),
333 locked_data_() {
334 io_thread_data_.channel_ = IPC::Channel::CreateServer(handle, this);
335 // Note, we can not PostTask for ConnectChannelOnIOThread here. If we did,
336 // and that task ran before this constructor completes, the reference count
337 // would go to 1 and then to 0 because of the Task, before we've been returned
338 // to the owning scoped_refptr, which is supposed to give us our first
339 // ref-count.
342 NaClIPCAdapter::NaClIPCAdapter(scoped_ptr<IPC::Channel> channel,
343 base::TaskRunner* runner)
344 : lock_(),
345 cond_var_(&lock_),
346 task_runner_(runner),
347 locked_data_() {
348 io_thread_data_.channel_ = channel.Pass();
351 void NaClIPCAdapter::ConnectChannel() {
352 task_runner_->PostTask(FROM_HERE,
353 base::Bind(&NaClIPCAdapter::ConnectChannelOnIOThread, this));
356 // Note that this message is controlled by the untrusted code. So we should be
357 // skeptical of anything it contains and quick to give up if anything is fishy.
358 int NaClIPCAdapter::Send(const NaClImcTypedMsgHdr* msg) {
359 if (msg->iov_length != 1)
360 return -1;
362 base::AutoLock lock(lock_);
364 const char* input_data = static_cast<char*>(msg->iov[0].base);
365 size_t input_data_len = msg->iov[0].length;
366 if (input_data_len > IPC::Channel::kMaximumMessageSize) {
367 ClearToBeSent();
368 return -1;
371 // current_message[_len] refers to the total input data received so far.
372 const char* current_message;
373 size_t current_message_len;
374 bool did_append_input_data;
375 if (locked_data_.to_be_sent_.empty()) {
376 // No accumulated data, we can avoid a copy by referring to the input
377 // buffer (the entire message fitting in one call is the common case).
378 current_message = input_data;
379 current_message_len = input_data_len;
380 did_append_input_data = false;
381 } else {
382 // We've already accumulated some data, accumulate this new data and
383 // point to the beginning of the buffer.
385 // Make sure our accumulated message size doesn't overflow our max. Since
386 // we know that data_len < max size (checked above) and our current
387 // accumulated value is also < max size, we just need to make sure that
388 // 2x max size can never overflow.
389 static_assert(IPC::Channel::kMaximumMessageSize < (UINT_MAX / 2),
390 "kMaximumMessageSize is too large, and may overflow");
391 size_t new_size = locked_data_.to_be_sent_.size() + input_data_len;
392 if (new_size > IPC::Channel::kMaximumMessageSize) {
393 ClearToBeSent();
394 return -1;
397 locked_data_.to_be_sent_.append(input_data, input_data_len);
398 current_message = &locked_data_.to_be_sent_[0];
399 current_message_len = locked_data_.to_be_sent_.size();
400 did_append_input_data = true;
403 // Check the total data we've accumulated so far to see if it contains a full
404 // message.
405 switch (GetBufferStatus(current_message, current_message_len)) {
406 case MESSAGE_IS_COMPLETE: {
407 // Got a complete message, can send it out. This will be the common case.
408 bool success = SendCompleteMessage(current_message, current_message_len);
409 ClearToBeSent();
410 return success ? static_cast<int>(input_data_len) : -1;
412 case MESSAGE_IS_TRUNCATED:
413 // For truncated messages, just accumulate the new data (if we didn't
414 // already do so above) and go back to waiting for more.
415 if (!did_append_input_data)
416 locked_data_.to_be_sent_.append(input_data, input_data_len);
417 return static_cast<int>(input_data_len);
418 case MESSAGE_HAS_EXTRA_DATA:
419 default:
420 // When the plugin gives us too much data, it's an error.
421 ClearToBeSent();
422 return -1;
426 int NaClIPCAdapter::BlockingReceive(NaClImcTypedMsgHdr* msg) {
427 if (msg->iov_length != 1)
428 return -1;
430 int retval = 0;
432 base::AutoLock lock(lock_);
433 while (locked_data_.to_be_received_.empty() &&
434 !locked_data_.channel_closed_)
435 cond_var_.Wait();
436 if (locked_data_.channel_closed_) {
437 retval = -1;
438 } else {
439 retval = LockedReceive(msg);
440 DCHECK(retval > 0);
442 cond_var_.Signal();
444 return retval;
447 void NaClIPCAdapter::CloseChannel() {
449 base::AutoLock lock(lock_);
450 locked_data_.channel_closed_ = true;
451 cond_var_.Signal();
454 task_runner_->PostTask(FROM_HERE,
455 base::Bind(&NaClIPCAdapter::CloseChannelOnIOThread, this));
458 NaClDesc* NaClIPCAdapter::MakeNaClDesc() {
459 return MakeNaClDescCustom(this);
462 #if defined(OS_POSIX)
463 base::ScopedFD NaClIPCAdapter::TakeClientFileDescriptor() {
464 return io_thread_data_.channel_->TakeClientFileDescriptor();
466 #endif
468 bool NaClIPCAdapter::OnMessageReceived(const IPC::Message& msg) {
469 uint32_t type = msg.type();
471 if (type == IPC_REPLY_ID) {
472 int id = IPC::SyncMessage::GetMessageId(msg);
473 IOThreadData::PendingSyncMsgMap::iterator it =
474 io_thread_data_.pending_sync_msgs_.find(id);
475 DCHECK(it != io_thread_data_.pending_sync_msgs_.end());
476 if (it != io_thread_data_.pending_sync_msgs_.end()) {
477 type = it->second;
478 io_thread_data_.pending_sync_msgs_.erase(it);
481 // Handle PpapiHostMsg_OpenResource outside the lock as it requires sending
482 // IPC to handle properly.
483 if (type == PpapiHostMsg_OpenResource::ID) {
484 base::PickleIterator iter = IPC::SyncMessage::GetDataIterator(&msg);
485 ppapi::proxy::SerializedHandle sh;
486 uint64_t token_lo;
487 uint64_t token_hi;
488 if (!IPC::ReadParam(&msg, &iter, &sh) ||
489 !IPC::ReadParam(&msg, &iter, &token_lo) ||
490 !IPC::ReadParam(&msg, &iter, &token_hi)) {
491 return false;
494 if (sh.IsHandleValid() && (token_lo != 0 || token_hi != 0)) {
495 // We've received a valid file token. Instead of using the file
496 // descriptor received, we send the file token to the browser in
497 // exchange for a new file descriptor and file path information.
498 // That file descriptor can be used to construct a NaClDesc with
499 // identity-based validation caching.
501 // We do not use file descriptors from the renderer with validation
502 // caching; a compromised renderer should not be able to run
503 // arbitrary code in a plugin process.
504 DCHECK(!resolve_file_token_cb_.is_null());
506 // resolve_file_token_cb_ must be invoked from the I/O thread.
507 resolve_file_token_cb_.Run(
508 token_lo,
509 token_hi,
510 base::Bind(&NaClIPCAdapter::SaveOpenResourceMessage,
511 this,
512 msg));
514 // In this case, we don't release the message to NaCl untrusted code
515 // immediately. We defer it until we get an async message back from the
516 // browser process.
517 return true;
520 return RewriteMessage(msg, type);
523 bool NaClIPCAdapter::RewriteMessage(const IPC::Message& msg, uint32_t type) {
525 base::AutoLock lock(lock_);
526 scoped_refptr<RewrittenMessage> rewritten_msg(new RewrittenMessage);
528 typedef std::vector<ppapi::proxy::SerializedHandle> Handles;
529 Handles handles;
530 scoped_ptr<IPC::Message> new_msg;
532 if (!locked_data_.nacl_msg_scanner_.ScanMessage(
533 msg, type, &handles, &new_msg))
534 return false;
536 // Now add any descriptors we found to rewritten_msg. |handles| is usually
537 // empty, unless we read a message containing a FD or handle.
538 for (Handles::const_iterator iter = handles.begin();
539 iter != handles.end();
540 ++iter) {
541 scoped_ptr<NaClDescWrapper> nacl_desc;
542 switch (iter->type()) {
543 case ppapi::proxy::SerializedHandle::SHARED_MEMORY: {
544 const base::SharedMemoryHandle& shm_handle = iter->shmem();
545 uint32_t size = iter->size();
546 nacl_desc.reset(new NaClDescWrapper(NaClDescImcShmMake(
547 #if defined(OS_WIN)
548 shm_handle,
549 #else
550 base::SharedMemory::GetFdFromSharedMemoryHandle(shm_handle),
551 #endif
552 static_cast<size_t>(size))));
553 break;
555 case ppapi::proxy::SerializedHandle::SOCKET: {
556 nacl_desc.reset(new NaClDescWrapper(NaClDescSyncSocketMake(
557 #if defined(OS_WIN)
558 iter->descriptor()
559 #else
560 iter->descriptor().fd
561 #endif
562 )));
563 break;
565 case ppapi::proxy::SerializedHandle::FILE: {
566 // Create the NaClDesc for the file descriptor. If quota checking is
567 // required, wrap it in a NaClDescQuota.
568 NaClDesc* desc = NaClDescIoMakeFromHandle(
569 #if defined(OS_WIN)
570 iter->descriptor(),
571 #else
572 iter->descriptor().fd,
573 #endif
574 TranslatePepperFileReadWriteOpenFlags(iter->open_flags()));
575 if (desc && iter->file_io()) {
576 desc = MakeNaClDescQuota(
577 locked_data_.nacl_msg_scanner_.GetFile(iter->file_io()),
578 desc);
580 if (desc)
581 nacl_desc.reset(new NaClDescWrapper(desc));
582 break;
585 case ppapi::proxy::SerializedHandle::INVALID: {
586 // Nothing to do.
587 break;
589 // No default, so the compiler will warn us if new types get added.
591 if (nacl_desc.get())
592 rewritten_msg->AddDescriptor(nacl_desc.release());
594 if (new_msg)
595 SaveMessage(*new_msg, rewritten_msg.get());
596 else
597 SaveMessage(msg, rewritten_msg.get());
598 cond_var_.Signal();
600 return true;
603 scoped_ptr<IPC::Message> CreateOpenResourceReply(
604 const IPC::Message& orig_msg,
605 ppapi::proxy::SerializedHandle sh) {
606 // The creation of new_msg must be kept in sync with
607 // SyncMessage::WriteSyncHeader.
608 scoped_ptr<IPC::Message> new_msg(new IPC::Message(
609 orig_msg.routing_id(),
610 orig_msg.type(),
611 IPC::Message::PRIORITY_NORMAL));
612 new_msg->set_reply();
613 new_msg->WriteInt(IPC::SyncMessage::GetMessageId(orig_msg));
615 ppapi::proxy::SerializedHandle::WriteHeader(sh.header(),
616 new_msg.get());
617 new_msg->WriteBool(true); // valid == true
618 // The file descriptor is at index 0. There's only ever one file
619 // descriptor provided for this message type, so this will be correct.
620 new_msg->WriteInt(0);
622 // Write empty file tokens.
623 new_msg->WriteUInt64(0); // token_lo
624 new_msg->WriteUInt64(0); // token_hi
625 return new_msg.Pass();
628 void NaClIPCAdapter::SaveOpenResourceMessage(
629 const IPC::Message& orig_msg,
630 IPC::PlatformFileForTransit ipc_fd,
631 base::FilePath file_path) {
632 // The path where an invalid ipc_fd is returned isn't currently
633 // covered by any tests.
634 if (ipc_fd == IPC::InvalidPlatformFileForTransit()) {
635 // The file token didn't resolve successfully, so we give the
636 // original FD to the client without making a validated NaClDesc.
637 // However, we must rewrite the message to clear the file tokens.
638 base::PickleIterator iter = IPC::SyncMessage::GetDataIterator(&orig_msg);
639 ppapi::proxy::SerializedHandle sh;
641 // We know that this can be read safely; see the original read in
642 // OnMessageReceived().
643 CHECK(IPC::ReadParam(&orig_msg, &iter, &sh));
644 scoped_ptr<IPC::Message> new_msg = CreateOpenResourceReply(orig_msg, sh);
646 scoped_ptr<NaClDescWrapper> desc_wrapper(new NaClDescWrapper(
647 NaClDescIoMakeFromHandle(
648 #if defined(OS_WIN)
649 sh.descriptor(),
650 #else
651 sh.descriptor().fd,
652 #endif
653 NACL_ABI_O_RDONLY)));
655 scoped_refptr<RewrittenMessage> rewritten_msg(new RewrittenMessage);
656 rewritten_msg->AddDescriptor(desc_wrapper.release());
658 base::AutoLock lock(lock_);
659 SaveMessage(*new_msg, rewritten_msg.get());
660 cond_var_.Signal();
662 return;
665 // The file token was sucessfully resolved.
666 std::string file_path_str = file_path.AsUTF8Unsafe();
667 base::PlatformFile handle =
668 IPC::PlatformFileForTransitToPlatformFile(ipc_fd);
670 ppapi::proxy::SerializedHandle sh;
671 sh.set_file_handle(ipc_fd, PP_FILEOPENFLAG_READ, 0);
672 scoped_ptr<IPC::Message> new_msg = CreateOpenResourceReply(orig_msg, sh);
673 scoped_refptr<RewrittenMessage> rewritten_msg(new RewrittenMessage);
675 struct NaClDesc* desc =
676 NaClDescCreateWithFilePathMetadata(handle, file_path_str.c_str());
677 rewritten_msg->AddDescriptor(new NaClDescWrapper(desc));
679 base::AutoLock lock(lock_);
680 SaveMessage(*new_msg, rewritten_msg.get());
681 cond_var_.Signal();
685 void NaClIPCAdapter::OnChannelConnected(int32 peer_pid) {
688 void NaClIPCAdapter::OnChannelError() {
689 CloseChannel();
692 NaClIPCAdapter::~NaClIPCAdapter() {
693 // Make sure the channel is deleted on the IO thread.
694 task_runner_->PostTask(FROM_HERE,
695 base::Bind(&DeleteChannel, io_thread_data_.channel_.release()));
698 int NaClIPCAdapter::LockedReceive(NaClImcTypedMsgHdr* msg) {
699 lock_.AssertAcquired();
701 if (locked_data_.to_be_received_.empty())
702 return 0;
703 scoped_refptr<RewrittenMessage> current =
704 locked_data_.to_be_received_.front();
706 int retval = current->Read(msg);
708 // When a message is entirely consumed, remove if from the waiting queue.
709 if (current->is_consumed())
710 locked_data_.to_be_received_.pop();
712 return retval;
715 bool NaClIPCAdapter::SendCompleteMessage(const char* buffer,
716 size_t buffer_len) {
717 lock_.AssertAcquired();
718 // The message will have already been validated, so we know it's large enough
719 // for our header.
720 const NaClMessageHeader* header =
721 reinterpret_cast<const NaClMessageHeader*>(buffer);
723 // Length of the message not including the body. The data passed to us by the
724 // plugin should match that in the message header. This should have already
725 // been validated by GetBufferStatus.
726 int body_len = static_cast<int>(buffer_len - sizeof(NaClMessageHeader));
727 DCHECK(body_len == static_cast<int>(header->payload_size));
729 // We actually discard the flags and only copy the ones we care about. This
730 // is just because message doesn't have a constructor that takes raw flags.
731 scoped_ptr<IPC::Message> msg(
732 new IPC::Message(header->routing, header->type,
733 IPC::Message::PRIORITY_NORMAL));
734 if (header->flags & IPC::Message::SYNC_BIT)
735 msg->set_sync();
736 if (header->flags & IPC::Message::REPLY_BIT)
737 msg->set_reply();
738 if (header->flags & IPC::Message::REPLY_ERROR_BIT)
739 msg->set_reply_error();
740 if (header->flags & IPC::Message::UNBLOCK_BIT)
741 msg->set_unblock(true);
743 msg->WriteBytes(&buffer[sizeof(NaClMessageHeader)], body_len);
745 // Technically we didn't have to do any of the previous work in the lock. But
746 // sometimes our buffer will point to the to_be_sent_ string which is
747 // protected by the lock, and it's messier to factor Send() such that it can
748 // unlock for us. Holding the lock for the message construction, which is
749 // just some memcpys, shouldn't be a big deal.
750 lock_.AssertAcquired();
751 if (locked_data_.channel_closed_) {
752 // If we ever pass handles from the plugin to the host, we should close them
753 // here before we drop the message.
754 return false;
757 // Scan all untrusted messages.
758 scoped_ptr<IPC::Message> new_msg;
759 locked_data_.nacl_msg_scanner_.ScanUntrustedMessage(*msg, &new_msg);
760 if (new_msg)
761 msg.reset(new_msg.release());
763 // Actual send must be done on the I/O thread.
764 task_runner_->PostTask(FROM_HERE,
765 base::Bind(&NaClIPCAdapter::SendMessageOnIOThread, this,
766 base::Passed(&msg)));
767 return true;
770 void NaClIPCAdapter::ClearToBeSent() {
771 lock_.AssertAcquired();
773 // Don't let the string keep its buffer behind our back.
774 std::string empty;
775 locked_data_.to_be_sent_.swap(empty);
778 void NaClIPCAdapter::ConnectChannelOnIOThread() {
779 if (!io_thread_data_.channel_->Connect())
780 NOTREACHED();
783 void NaClIPCAdapter::CloseChannelOnIOThread() {
784 io_thread_data_.channel_->Close();
787 void NaClIPCAdapter::SendMessageOnIOThread(scoped_ptr<IPC::Message> message) {
788 int id = IPC::SyncMessage::GetMessageId(*message.get());
789 DCHECK(io_thread_data_.pending_sync_msgs_.find(id) ==
790 io_thread_data_.pending_sync_msgs_.end());
792 // Handle PpapiHostMsg_OpenResource locally without sending an IPC to the
793 // renderer when possible.
794 PpapiHostMsg_OpenResource::Schema::SendParam send_params;
795 if (!open_resource_cb_.is_null() &&
796 message->type() == PpapiHostMsg_OpenResource::ID &&
797 PpapiHostMsg_OpenResource::ReadSendParam(message.get(), &send_params)) {
798 const std::string key = base::get<0>(send_params);
799 // Both open_resource_cb_ and SaveOpenResourceMessage must be invoked
800 // from the I/O thread.
801 if (open_resource_cb_.Run(
802 *message.get(), key,
803 base::Bind(&NaClIPCAdapter::SaveOpenResourceMessage, this))) {
804 // The callback sent a reply to the untrusted side.
805 return;
809 if (message->is_sync())
810 io_thread_data_.pending_sync_msgs_[id] = message->type();
811 io_thread_data_.channel_->Send(message.release());
814 void NaClIPCAdapter::SaveMessage(const IPC::Message& msg,
815 RewrittenMessage* rewritten_msg) {
816 lock_.AssertAcquired();
817 // There is some padding in this structure (the "padding" member is 16
818 // bits but this then gets padded to 32 bits). We want to be sure not to
819 // leak data to the untrusted plugin, so zero everything out first.
820 NaClMessageHeader header;
821 memset(&header, 0, sizeof(NaClMessageHeader));
823 header.payload_size = static_cast<uint32>(msg.payload_size());
824 header.routing = msg.routing_id();
825 header.type = msg.type();
826 header.flags = msg.flags();
827 header.num_fds = static_cast<uint16>(rewritten_msg->desc_count());
829 rewritten_msg->SetData(header, msg.payload(), msg.payload_size());
830 locked_data_.to_be_received_.push(rewritten_msg);
833 int TranslatePepperFileReadWriteOpenFlagsForTesting(int32_t pp_open_flags) {
834 return TranslatePepperFileReadWriteOpenFlags(pp_open_flags);