1

假设我有一个这样的流 API:

interface MyInterface {
  addListener @0 (listener: Listener) -> (registration: RegisteredListener);

  interface Listener {
    update @0 () -> stream;
  }
  interface RegisteredListener {
  }
}

我遇到了一个挑战,即服务器实现的析构函数MyInterface在最后一个注册接口发布之前运行。如何正确地将关系传达给 cap'n'proto RPC,这样即使客户端MyInterface::Client在 或者,我是否以某种基本方式滥用 API?RegisteredListener::ClientMyInterface::ServerRegisteredListener::Server

C++ 代码大致如下所示。服务器:

class MyInterfaceImpl : public MyInterface {
 class Registered final : public MyInterface::RegisteredListener::Server {
  public:
   Registered(MyInterfaceImpl* parent, uint64_t registrationId) : parent_(parent), id_(registrationId) {}

   ~Registered() {
     parent->unregister(id_);
   }
  private:
   MyInterfaceImpl *parent_;
   uint64_t id_;
 };

 public:
  kj::Promise<void> addListener(MyInterface::AddListenerContext context) {
    auto registrationId = ++registrationId_;
    clients_.emplace_back(context.getParams().getListener());
    registrations_.emplace_back(registrationId);
    context.getResult().setRegistration(kj::heap<Registered>(this, registrationId));
    return kj::READY_NOW;
  }

  void unregister(uint64_t registrationId) {
    auto found = std::find(registrations_.begin(), registrations_.end(), registrationId);
    clients_.erase(clients_.begin() + (found - registrations_.begin()));
  }

 private:
  std::vector<MyInterface::Listener::Client> clients_;
  std::vector<uint64_t> registrations_;
  uint64_t registrationId_ = 0;
};

客户端代码如下所示:

capnp::EzRpcClient client("localhost:5923");
MyInterface::Client intf = client.getMain<MyInterface>();
auto& waitScope = client.getWaitScope();

auto listenerRequest = intf.addListenerRequest();
auto listenerPromise = listenerRequest.send();
listenerPromise.wait(waitScope);

{
  auto listenerRequest2 = intf.addListenerRequest();
  auto listenerPromise2 = listenerRequest2.send();
  listenerPromise2.wait(waitScope);
}

由于这都是单线程的,因此很容易发现 use-after-free。我将调试语句放入~MyInterfaceImpl并且~RegisteredListener第二个侦听器在~MyInterfaceImpl. 我知道我的添加侦听器请求没有实际的客户端对象,但我希望这实际上不是一个重要的细节。

4

1 回答 1

0

除了当前持有的普通指针之外,我建议让Registered类持有MyInterface::Client指向父级的指针。

MyInterfaceImpl *parent_;
MyInterface::Client ownParent_;
uint64_t id_;

这确保了只要 aRegistered仍然存在,MyInterfaceImpl就不会被破坏。

在 的实现内部addListener(),您可以通过MyInterface::Client调用.thisthisCap()

context.getResult().setRegistration(kj::heap<Registered>(
    this, thisCap(), registrationId));
于 2020-06-30T00:22:59.083 回答