Home | History | Annotate | Download | only in core
      1 // Copyright 2018 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.
      4 
      5 #include "mojo/core/invitation_dispatcher.h"
      6 
      7 #include "mojo/core/core.h"
      8 
      9 namespace mojo {
     10 namespace core {
     11 
     12 InvitationDispatcher::InvitationDispatcher() = default;
     13 
     14 Dispatcher::Type InvitationDispatcher::GetType() const {
     15   return Type::INVITATION;
     16 }
     17 
     18 MojoResult InvitationDispatcher::Close() {
     19   PortMapping attached_ports;
     20   {
     21     base::AutoLock lock(lock_);
     22     if (is_closed_)
     23       return MOJO_RESULT_INVALID_ARGUMENT;
     24     is_closed_ = true;
     25     std::swap(attached_ports, attached_ports_);
     26   }
     27   for (auto& entry : attached_ports)
     28     Core::Get()->GetNodeController()->ClosePort(entry.second);
     29   return MOJO_RESULT_OK;
     30 }
     31 
     32 MojoResult InvitationDispatcher::AttachMessagePipe(
     33     base::StringPiece name,
     34     ports::PortRef remote_peer_port) {
     35   base::AutoLock lock(lock_);
     36   auto result = attached_ports_.emplace(name.as_string(), remote_peer_port);
     37   if (!result.second) {
     38     Core::Get()->GetNodeController()->ClosePort(remote_peer_port);
     39     return MOJO_RESULT_ALREADY_EXISTS;
     40   }
     41   return MOJO_RESULT_OK;
     42 }
     43 
     44 MojoResult InvitationDispatcher::ExtractMessagePipe(
     45     base::StringPiece name,
     46     MojoHandle* message_pipe_handle) {
     47   ports::PortRef remote_peer_port;
     48   {
     49     base::AutoLock lock(lock_);
     50     auto it = attached_ports_.find(name.as_string());
     51     if (it == attached_ports_.end())
     52       return MOJO_RESULT_NOT_FOUND;
     53     remote_peer_port = std::move(it->second);
     54     attached_ports_.erase(it);
     55   }
     56 
     57   *message_pipe_handle =
     58       Core::Get()->CreatePartialMessagePipe(remote_peer_port);
     59   if (*message_pipe_handle == MOJO_HANDLE_INVALID)
     60     return MOJO_RESULT_RESOURCE_EXHAUSTED;
     61   return MOJO_RESULT_OK;
     62 }
     63 
     64 InvitationDispatcher::PortMapping InvitationDispatcher::TakeAttachedPorts() {
     65   PortMapping attached_ports;
     66   {
     67     base::AutoLock lock(lock_);
     68     std::swap(attached_ports, attached_ports_);
     69   }
     70   return attached_ports;
     71 }
     72 
     73 InvitationDispatcher::~InvitationDispatcher() {
     74   DCHECK(is_closed_);
     75 }
     76 
     77 }  // namespace core
     78 }  // namespace mojo
     79