From 8386482fb9ee76bcfa79ba11915a9bcdf9745948 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Roman=20Smr=C5=BE?= Date: Sun, 7 May 2023 22:28:12 +0200 Subject: Server function to manually add peer --- src/network.cpp | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) (limited to 'src/network.cpp') diff --git a/src/network.cpp b/src/network.cpp index ecf7ca0..226095b 100644 --- a/src/network.cpp +++ b/src/network.cpp @@ -11,6 +11,9 @@ #include #include #include +#include +#include +#include #include using std::get; @@ -70,6 +73,43 @@ PeerList & Server::peerList() const return p->plist; } +void Server::addPeer(const string & node) const +{ + return addPeer(node, to_string(Priv::discoveryPort)); +} + +void Server::addPeer(const string & node, const string & service) const +{ + addrinfo hints {}; + hints.ai_flags = AI_V4MAPPED | AI_ADDRCONFIG; + hints.ai_family = AF_INET6; + hints.ai_socktype = SOCK_DGRAM; + addrinfo *aptr; + + int r = getaddrinfo(node.c_str(), service.c_str(), &hints, &aptr); + if (r != 0) + throw runtime_error(string("Server::addPeer: getaddrinfo failed: ") + gai_strerror(r)); + + unique_ptr result { aptr, &freeaddrinfo }; + + for (addrinfo * rp = result.get(); rp != nullptr; rp = rp->ai_next) { + if (rp->ai_family == AF_INET6) { + Peer & peer = p->getPeer(*(sockaddr_in6 *)rp->ai_addr); + + vector header; + { + shared_lock lock(p->selfMutex); + header.push_back(TransportHeader::Item { + TransportHeader::Type::AnnounceSelf, *p->self.ref() }); + } + peer.send(header, {}, false); + return; + } + } + + throw runtime_error("Server::addPeer: no suitable peer address found"); +} + Peer::Peer(const shared_ptr & p): p(p) {} Peer::~Peer() = default; @@ -424,6 +464,8 @@ bool Server::Priv::isSelfAddress(const sockaddr_in6 & paddr) Server::Peer & Server::Priv::getPeer(const sockaddr_in6 & paddr) { + scoped_lock lock(dataMutex); + for (auto & peer : peers) if (memcmp(&peer->addr, &paddr, sizeof paddr) == 0) return *peer; -- cgit v1.2.3