diff --git a/src/UDPC_Defines.hpp b/src/UDPC_Defines.hpp index 46d036f..c506faf 100644 --- a/src/UDPC_Defines.hpp +++ b/src/UDPC_Defines.hpp @@ -230,7 +230,6 @@ public: std::atomic_uint_fast8_t loggingType; // See UDPC_AuthPolicy enum in UDPC.h for possible values std::atomic_uint_fast8_t authPolicy; - std::atomic_uint32_t atostrBufIndex; char atostrBuf[UDPC_ATOSTR_SIZE]; UDPC_SOCKETTYPE socketHandle; @@ -267,6 +266,9 @@ public: unsigned char pk[crypto_sign_PUBLICKEYBYTES]; std::atomic_bool keysSet; + std::mutex atostrBufIndexMutex; + std::uint32_t atostrBufIndex; + }; // struct Context Context *verifyContext(UDPC_HContext ctx); diff --git a/src/UDPConnection.cpp b/src/UDPConnection.cpp index 8f9e327..5de1052 100644 --- a/src/UDPConnection.cpp +++ b/src/UDPConnection.cpp @@ -223,12 +223,12 @@ loggingType(UDPC_DEBUG), #else loggingType(UDPC_WARNING), #endif -atostrBufIndex(0), receivedPkts(), cSendPkts(), rng_engine(), conMapMutex(), -peerPKWhitelistMutex() +peerPKWhitelistMutex(), +atostrBufIndex(0) { std::memset(atostrBuf, 0, UDPC_ATOSTR_SIZE); @@ -2633,8 +2633,13 @@ const char *UDPC_atostr(UDPC_HContext ctx, UDPC_IPV6_ADDR_TYPE addr) { if(!c) { return nullptr; } - const uint32_t headIndex = - c->atostrBufIndex.fetch_add(UDPC_ATOSTR_BUFSIZE) % UDPC_ATOSTR_SIZE; + uint32_t headIndex; + { + // Use a lock to ensure that "atostrBufIndex" is always a valid value. + std::lock_guard indexLock(c->atostrBufIndexMutex); + c->atostrBufIndex = (c->atostrBufIndex + UDPC_ATOSTR_BUFSIZE) % UDPC_ATOSTR_SIZE; + headIndex = c->atostrBufIndex; + } uint32_t index = headIndex; bool usedDouble = false;