From 4a6744846e5b19d3f5741780d9082bed5244af06 Mon Sep 17 00:00:00 2001 From: m8mble Date: Fri, 20 Jan 2023 16:36:30 +0100 Subject: [PATCH] Fix exception in server It can happen that a connection handler calls writefun when the connection is already destroyed. This causes bad_weak_ptr exceptions thrown from the server. Fix this issue by skipping the respective do_write invocations. --- lib/asio_server_connection.h | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/lib/asio_server_connection.h b/lib/asio_server_connection.h index a948965..f2dc954 100644 --- a/lib/asio_server_connection.h +++ b/lib/asio_server_connection.h @@ -88,9 +88,20 @@ class connection : public std::enable_shared_from_this>, void start() { boost::system::error_code ec; + auto make_writefun = [this] { + return [weak = std::weak_ptr{this->shared_from_this()}]() { + auto self = weak.lock(); + // If connection already got destroyed, the socket is already closed in particular. + // Therefore we can simply ignore further calls to write. + if (self) { + self->do_write(); + } + }; + }; + handler_ = std::make_shared( GET_IO_SERVICE(socket_), socket_.lowest_layer().remote_endpoint(ec), - [this]() { do_write(); }, mux_); + make_writefun(), mux_); if (handler_->start() != 0) { stop(); return;