-
-
Notifications
You must be signed in to change notification settings - Fork 473
Solves websocket memory leak #1080
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
Open
StefanoPetrilli
wants to merge
3
commits into
CrowCpp:master
Choose a base branch
from
StefanoPetrilli:removes-websocket-connection-raw-pointers
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+87
−83
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,5 +1,6 @@ | ||
#pragma once | ||
#include <array> | ||
#include <memory> | ||
#include "crow/logging.h" | ||
#include "crow/socket_adaptors.h" | ||
#include "crow/http_request.h" | ||
|
@@ -102,36 +103,31 @@ namespace crow // NOTE: Already documented in "crow/app.h" | |
/// A websocket connection. | ||
|
||
template<typename Adaptor, typename Handler> | ||
class Connection : public connection | ||
class Connection : public connection, public std::enable_shared_from_this<Connection<Adaptor, Handler>> | ||
{ | ||
public: | ||
/// Constructor for a connection. | ||
|
||
/// Factory for a connection. | ||
/// | ||
/// Requires a request with an "Upgrade: websocket" header.<br> | ||
/// Automatically handles the handshake. | ||
Connection(const crow::request& req, Adaptor&& adaptor, Handler* handler, | ||
uint64_t max_payload, const std::vector<std::string>& subprotocols, | ||
std::function<void(crow::websocket::connection&)> open_handler, | ||
std::function<void(crow::websocket::connection&, const std::string&, bool)> message_handler, | ||
std::function<void(crow::websocket::connection&, const std::string&, uint16_t)> close_handler, | ||
std::function<void(crow::websocket::connection&, const std::string&)> error_handler, | ||
std::function<bool(const crow::request&, void**)> accept_handler, | ||
bool mirror_protocols): | ||
adaptor_(std::move(adaptor)), | ||
handler_(handler), | ||
max_payload_bytes_(max_payload), | ||
open_handler_(std::move(open_handler)), | ||
message_handler_(std::move(message_handler)), | ||
close_handler_(std::move(close_handler)), | ||
error_handler_(std::move(error_handler)), | ||
accept_handler_(std::move(accept_handler)) | ||
static void create(const crow::request& req, Adaptor adaptor, Handler* handler, | ||
uint64_t max_payload, const std::vector<std::string>& subprotocols, | ||
std::function<void(crow::websocket::connection&)> open_handler, | ||
std::function<void(crow::websocket::connection&, const std::string&, bool)> message_handler, | ||
std::function<void(crow::websocket::connection&, const std::string&, uint16_t)> close_handler, | ||
std::function<void(crow::websocket::connection&, const std::string&)> error_handler, | ||
std::function<bool(const crow::request&, void**)> accept_handler, | ||
bool mirror_protocols) | ||
{ | ||
auto conn = std::shared_ptr<Connection>( | ||
new Connection(std::move(adaptor), handler, max_payload, | ||
std::move(open_handler), std::move(message_handler), std::move(close_handler), | ||
std::move(error_handler), std::move(accept_handler))); | ||
|
||
// Perform handshake validation | ||
if (!utility::string_equals(req.get_header_value("upgrade"), "websocket")) | ||
{ | ||
adaptor_.close(); | ||
handler_->remove_websocket(this); | ||
delete this; | ||
conn->adaptor_.close(); | ||
return; | ||
} | ||
|
||
|
@@ -142,26 +138,24 @@ namespace crow // NOTE: Already documented in "crow/app.h" | |
auto subprotocol = utility::find_first_of(subprotocols.begin(), subprotocols.end(), requested_subprotocols.begin(), requested_subprotocols.end()); | ||
if (subprotocol != subprotocols.end()) | ||
{ | ||
subprotocol_ = *subprotocol; | ||
conn->subprotocol_ = *subprotocol; | ||
} | ||
} | ||
|
||
if (mirror_protocols & !requested_subprotocols_header.empty()) | ||
{ | ||
subprotocol_ = requested_subprotocols_header; | ||
conn->subprotocol_ = requested_subprotocols_header; | ||
} | ||
|
||
if (accept_handler_) | ||
if (conn->accept_handler_) | ||
{ | ||
void* ud = nullptr; | ||
if (!accept_handler_(req, &ud)) | ||
if (!conn->accept_handler_(req, &ud)) | ||
{ | ||
adaptor_.close(); | ||
handler_->remove_websocket(this); | ||
delete this; | ||
conn->adaptor_.close(); | ||
return; | ||
} | ||
userdata(ud); | ||
conn->userdata(ud); | ||
} | ||
|
||
// Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ== | ||
|
@@ -172,22 +166,11 @@ namespace crow // NOTE: Already documented in "crow/app.h" | |
uint8_t digest[20]; | ||
s.getDigestBytes(digest); | ||
|
||
start(crow::utility::base64encode((unsigned char*)digest, 20)); | ||
conn->handler_->add_websocket(conn); | ||
conn->start(crow::utility::base64encode((unsigned char*)digest, 20)); | ||
} | ||
|
||
~Connection() noexcept override | ||
{ | ||
// Do not modify anchor_ here since writing shared_ptr is not atomic. | ||
auto watch = std::weak_ptr<void>{anchor_}; | ||
|
||
// Wait until all unhandled asynchronous operations to join. | ||
// As the deletion occurs inside 'check_destroy()', which already locks | ||
// anchor, use count can be 1 on valid deletion context. | ||
while (watch.use_count() > 2) // 1 for 'check_destroy() routine', 1 for 'this->anchor_' | ||
{ | ||
std::this_thread::yield(); | ||
} | ||
} | ||
~Connection() noexcept override = default; | ||
|
||
template<typename Callable> | ||
struct WeakWrappedMessage | ||
|
@@ -717,38 +700,38 @@ namespace crow // NOTE: Already documented in "crow/app.h" | |
/// Also destroys the object if the Close flag is set. | ||
void do_write() | ||
{ | ||
if (sending_buffers_.empty()) | ||
if (write_buffers_.empty()) return; | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This was checking the wrong buffer, update to check |
||
|
||
sending_buffers_.swap(write_buffers_); | ||
std::vector<asio::const_buffer> buffers; | ||
buffers.reserve(sending_buffers_.size()); | ||
for (auto& s : sending_buffers_) | ||
{ | ||
sending_buffers_.swap(write_buffers_); | ||
std::vector<asio::const_buffer> buffers; | ||
buffers.reserve(sending_buffers_.size()); | ||
for (auto& s : sending_buffers_) | ||
{ | ||
buffers.emplace_back(asio::buffer(s)); | ||
} | ||
auto watch = std::weak_ptr<void>{anchor_}; | ||
asio::async_write( | ||
adaptor_.socket(), buffers, | ||
[&, watch](const error_code& ec, std::size_t /*bytes_transferred*/) { | ||
if (!ec && !close_connection_) | ||
{ | ||
sending_buffers_.clear(); | ||
if (!write_buffers_.empty()) | ||
do_write(); | ||
if (has_sent_close_) | ||
close_connection_ = true; | ||
} | ||
else | ||
{ | ||
auto anchor = watch.lock(); | ||
if (anchor == nullptr) { return; } | ||
|
||
sending_buffers_.clear(); | ||
close_connection_ = true; | ||
check_destroy(); | ||
} | ||
}); | ||
buffers.emplace_back(asio::buffer(s)); | ||
} | ||
auto watch = std::weak_ptr<void>{anchor_}; | ||
asio::async_write( | ||
adaptor_.socket(), buffers, | ||
[this, watch](const error_code& ec, std::size_t /*bytes_transferred*/) { | ||
auto anchor = watch.lock(); | ||
if (anchor == nullptr) | ||
return; | ||
|
||
if (!ec && !close_connection_) | ||
{ | ||
sending_buffers_.clear(); | ||
if (!write_buffers_.empty()) | ||
do_write(); | ||
if (has_sent_close_) | ||
close_connection_ = true; | ||
} | ||
else | ||
{ | ||
sending_buffers_.clear(); | ||
close_connection_ = true; | ||
check_destroy(); | ||
} | ||
}); | ||
} | ||
|
||
/// Destroy the Connection. | ||
|
@@ -757,11 +740,14 @@ namespace crow // NOTE: Already documented in "crow/app.h" | |
// Note that if the close handler was not yet called at this point we did not receive a close packet (or send one) | ||
// and thus we use ClosedAbnormally unless instructed otherwise | ||
if (!is_close_handler_called_) | ||
{ | ||
if (close_handler_) | ||
{ | ||
close_handler_(*this, "uncleanly", code); | ||
handler_->remove_websocket(this); | ||
if (sending_buffers_.empty() && !is_reading) | ||
delete this; | ||
} | ||
} | ||
|
||
handler_->remove_websocket(this->shared_from_this()); | ||
} | ||
|
||
|
||
|
@@ -796,6 +782,22 @@ namespace crow // NOTE: Already documented in "crow/app.h" | |
} | ||
|
||
private: | ||
Connection(Adaptor&& adaptor, Handler* handler, uint64_t max_payload, | ||
std::function<void(crow::websocket::connection&)> open_handler, | ||
std::function<void(crow::websocket::connection&, const std::string&, bool)> message_handler, | ||
std::function<void(crow::websocket::connection&, const std::string&, uint16_t)> close_handler, | ||
std::function<void(crow::websocket::connection&, const std::string&)> error_handler, | ||
std::function<bool(const crow::request&, void**)> accept_handler): | ||
adaptor_(std::move(adaptor)), | ||
handler_(handler), | ||
max_payload_bytes_(max_payload), | ||
open_handler_(std::move(open_handler)), | ||
message_handler_(std::move(message_handler)), | ||
close_handler_(std::move(close_handler)), | ||
error_handler_(std::move(error_handler)), | ||
accept_handler_(std::move(accept_handler)) | ||
{} | ||
|
||
Adaptor adaptor_; | ||
Handler* handler_; | ||
|
||
|
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
shoudn't std::make_shared(...) do the same as this function?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Ahh yes this is a good question, I should have probably explained this design choice.
To correctly keep track of the open
websockets::connection
s and destory them, we need to register them inApp::websockets_
once they are created.Inside the constructor the
shared_ptr
is not available yet so an option would be to add a method in theConnection
class to register itself to theApp::websockets_
. This would have been an easier solution but would have left the responsibility to the user to actually register thewebsocket::connection
after it is instantiated by calling the registration method.I think that the registration should instead happen by design. To achieve this I made the constructor private so that it's not possible to directly instantiate a
websocket::connection
. The instantiation is instead possible through this factory method. This factory instantiate, validates and registers the connection.Before, the constructor was taking care of validation as well while the registration was missing causing the memory leak.
Hope it was a clear explanation :)