Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Block possibility of using a stale reference in SafeQueue #913

Merged
merged 2 commits into from
Dec 16, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 3 additions & 9 deletions include/ocpp/common/safe_queue.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -13,22 +13,16 @@ namespace ocpp {
/// that can be waited upon. Will take up the waiting thread on each
/// operation of push/pop/clear
template <typename T> class SafeQueue {
using safe_queue_reference = typename std::queue<T>::reference;
using safe_queue_const_reference = typename std::queue<T>::const_reference;

public:
/// \return True if the queue is empty
inline bool empty() const {
std::lock_guard lock(mutex);
return queue.empty();
}

inline safe_queue_reference front() {
std::lock_guard lock(mutex);
return queue.front();
}

inline safe_queue_const_reference front() const {
/// \brief We return a copy here, since while might be accessing the
/// reference while another thread uses pop and makes the reference stale
inline T front() {
std::lock_guard lock(mutex);
return queue.front();
}
Expand Down
8 changes: 3 additions & 5 deletions lib/ocpp/common/websocket/websocket_libwebsockets.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1515,13 +1515,11 @@ void WebsocketLibwebsockets::on_conn_writable() {

// Execute while we have messages that were polled
while (true) {
WebsocketMessage* message = nullptr;

// Break if we have en empty queue
if (message_queue.empty())
break;

message = message_queue.front().get();
auto message = message_queue.front();

if (message == nullptr) {
EVLOG_AND_THROW(std::runtime_error("Null message in queue, fatal error!"));
Expand All @@ -1548,7 +1546,7 @@ void WebsocketLibwebsockets::on_conn_writable() {
// Poll a single message
EVLOG_debug << "Client writable, sending message part!";

WebsocketMessage* message = message_queue.front().get();
auto message = message_queue.front();

if (message == nullptr) {
EVLOG_AND_THROW(std::runtime_error("Null message in queue, fatal error!"));
Expand All @@ -1559,7 +1557,7 @@ void WebsocketLibwebsockets::on_conn_writable() {
}

// Continue sending message part, for a single message only
bool sent = send_internal(local_data->get_conn(), message);
bool sent = send_internal(local_data->get_conn(), message.get());

// If we failed, attempt again later
if (!sent) {
Expand Down