diff options
author | Roman Smrž <roman.smrz@seznam.cz> | 2023-05-07 22:28:12 +0200 |
---|---|---|
committer | Roman Smrž <roman.smrz@seznam.cz> | 2023-05-17 20:34:24 +0200 |
commit | 8386482fb9ee76bcfa79ba11915a9bcdf9745948 (patch) | |
tree | 675a88d31eabd7a6bf3a4c04912d7dbf7d85c0b7 /src/network.cpp | |
parent | 2d5508898e90c01680cab60295b9c1e8164d65da (diff) |
Server function to manually add peer
Diffstat (limited to 'src/network.cpp')
-rw-r--r-- | src/network.cpp | 42 |
1 files changed, 42 insertions, 0 deletions
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 <arpa/inet.h> #include <ifaddrs.h> #include <net/if.h> +#include <netdb.h> +#include <sys/socket.h> +#include <sys/types.h> #include <unistd.h> 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<addrinfo, void(*)(addrinfo*)> 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<TransportHeader::Item> 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<Priv> & 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; |