Skip to content

Commit

Permalink
Fix potential memory issue with websocket write buffers.
Browse files Browse the repository at this point in the history
  • Loading branch information
Kasper Peeters committed Dec 23, 2024
1 parent 66c9561 commit 2697a51
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 7 deletions.
3 changes: 2 additions & 1 deletion client_server/websocket_client.cc
Original file line number Diff line number Diff line change
Expand Up @@ -182,7 +182,8 @@ void websocket_client::do_write()
[this](boost::beast::error_code ec, std::size_t bytes_transferred) {
on_write(ec, bytes_transferred);
});
} else {
}
else {
ws_stream_->async_write(
msg.buffer->data(),
[this](boost::beast::error_code ec, std::size_t bytes_transferred) {
Expand Down
14 changes: 9 additions & 5 deletions client_server/websocket_server.cc
Original file line number Diff line number Diff line change
Expand Up @@ -124,8 +124,12 @@ void websocket_server::connection::send(const std::string& message)
{
if (!is_websocket_) return;

message_queue_.push(message);

queued_message msg;
msg.data = message;
msg.buffer = std::make_shared<boost::beast::flat_buffer>();
boost::beast::ostream(*msg.buffer) << msg.data;

message_queue_.push(msg);
if (!writing_) {
do_write();
}
Expand All @@ -140,10 +144,9 @@ void websocket_server::connection::do_write()

writing_ = true;
auto msg = message_queue_.front();
message_queue_.pop();

ws_stream_->async_write(
boost::asio::buffer(msg),
msg.buffer->data(),
[self = shared_from_this()](
boost::beast::error_code ec, std::size_t bytes_transferred) {
self->on_write(ec, bytes_transferred);
Expand All @@ -167,7 +170,8 @@ void websocket_server::connection::close()

void websocket_server::connection::on_write(boost::beast::error_code ec, std::size_t)
{
if (ec) {
message_queue_.pop();
if(ec) {
server_.remove_connection(id_);
return;
}
Expand Down
6 changes: 5 additions & 1 deletion client_server/websocket_server.hh
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,11 @@ class websocket_server {
websocket_server& server_;

id_type id_;
std::queue<std::string> message_queue_;
struct queued_message {
std::string data;
std::shared_ptr<boost::beast::flat_buffer> buffer;
};
std::queue<queued_message> message_queue_;
bool writing_{false};
bool is_websocket_{false};
};
Expand Down

0 comments on commit 2697a51

Please sign in to comment.