From 07f61b1ad6363cd471b7dab3f94c3160636fd6a0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Roman=20Smr=C5=BE?= Date: Sat, 6 May 2023 08:58:34 +0200 Subject: Server: do not return reference to self identity --- src/network.cpp | 14 ++++++++++---- src/network.h | 6 +++++- 2 files changed, 15 insertions(+), 5 deletions(-) (limited to 'src') diff --git a/src/network.cpp b/src/network.cpp index 8d318f7..dafab67 100644 --- a/src/network.cpp +++ b/src/network.cpp @@ -48,8 +48,9 @@ const Bhv & Server::localState() const return p->localState; } -const Identity & Server::identity() const +Identity Server::identity() const { + shared_lock lock(p->selfMutex); return p->self; } @@ -293,7 +294,7 @@ shared_ptr Server::Priv::getptr() void Server::Priv::doListen() { vector buf, decrypted, *current; - unique_lock lock(dataMutex); + unique_lock lock(dataMutex); for (; !finish; lock.lock()) { sockaddr_in paddr; @@ -340,7 +341,9 @@ void Server::Priv::doListen() ReplyBuilder reply; - scoped_lock hlock(dataMutex); + scoped_lock hlock(dataMutex); + shared_lock slock(selfMutex); + handlePacket(peer, *header, reply); peer.updateIdentity(reply); peer.updateChannel(reply); @@ -359,13 +362,14 @@ void Server::Priv::doListen() void Server::Priv::doAnnounce() { - unique_lock lock(dataMutex); + unique_lock lock(dataMutex); auto lastAnnounce = steady_clock::now() - announceInterval; while (!finish) { auto now = steady_clock::now(); if (lastAnnounce + announceInterval < now) { + shared_lock slock(selfMutex); TransportHeader header({ { TransportHeader::Type::AnnounceSelf, *self.ref() } }); @@ -578,6 +582,8 @@ void Server::Priv::handlePacket(Server::Peer & peer, const TransportHeader & hea void Server::Priv::handleLocalHeadChange(const Head & head) { scoped_lock lock(dataMutex); + scoped_lock slock(selfMutex); + if (auto id = head->identity()) { if (*id != self) { self = *id; diff --git a/src/network.h b/src/network.h index c620cf6..5a656cb 100644 --- a/src/network.h +++ b/src/network.h @@ -6,6 +6,7 @@ #include #include +#include #include #include @@ -15,6 +16,8 @@ using std::condition_variable; using std::monostate; using std::mutex; using std::optional; +using std::shared_lock; +using std::shared_mutex; using std::shared_ptr; using std::string; using std::thread; @@ -162,8 +165,9 @@ struct Server::Priv condition_variable announceCondvar; bool finish = false; + shared_mutex selfMutex; Identity self; - Bhv localState; + const Bhv localState; thread threadListen; thread threadAnnounce; -- cgit v1.2.3