Skip to content
Open
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
5 changes: 5 additions & 0 deletions include/libp2p/muxer/mplex/mplex_stream.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,11 @@ namespace libp2p::connection {
* @param data_size - size of the received data
*/
outcome::result<void> commitData(BytesIn data, size_t data_size);

/**
* Called by underlying connection to notify about closed connection
*/
void onConnectionClosed();
};
} // namespace libp2p::connection

Expand Down
2 changes: 1 addition & 1 deletion include/libp2p/muxer/yamux/yamux_stream.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ namespace libp2p::connection {
};

/// Performs close-related cleanup and notifications
void doClose(std::error_code ec);
void doClose(std::error_code ec, bool keepInternalBuffer = false);

/// Called by read*() functions
void doRead(BytesOut out, ReadCallbackFunc cb);
Expand Down
18 changes: 9 additions & 9 deletions src/muxer/mplex/mplex_stream.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ namespace libp2p::connection {
if (is_reset_) {
return cb(Error::STREAM_RESET_BY_PEER);
}
if (!is_readable_) {
if (!is_readable_ && read_buffer_.size() == 0) {
return cb(Error::STREAM_NOT_READABLE);
}
if (out.empty()) {
Expand Down Expand Up @@ -218,14 +218,6 @@ namespace libp2p::connection {

outcome::result<void> MplexStream::commitData(BytesIn data,
size_t data_size) {
if (data_size == 0) {
is_reset_ = true;
if (reading_.has_value()) {
readDone(Error::STREAM_RESET_BY_HOST);
}
return Error::STREAM_RESET_BY_HOST;
}

if (data_size > receive_window_size_) {
// we have received more data, than we can handle
reset();
Expand All @@ -247,6 +239,14 @@ namespace libp2p::connection {

return outcome::success();
}

void MplexStream::onConnectionClosed() {
is_readable_ = false;
if (reading_.has_value() && !readTry()) {
readDone(Error::STREAM_RESET_BY_HOST);
}
}

} // namespace libp2p::connection

size_t std::hash<libp2p::connection::MplexStream::StreamId>::operator()(
Expand Down
3 changes: 1 addition & 2 deletions src/muxer/mplex/mplexed_connection.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -326,8 +326,7 @@ namespace libp2p::connection {

void MplexedConnection::closeSession() {
for (auto &[_, stream] : streams_) {
// all that stuff to be refactored
(void)stream->commitData(BytesIn{}, 0);
stream->onConnectionClosed();
}

auto close_res = close();
Expand Down
8 changes: 5 additions & 3 deletions src/muxer/yamux/yamux_stream.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -302,10 +302,10 @@ namespace libp2p::connection {
}

void YamuxStream::closedByConnection(std::error_code ec) {
doClose(std::move(ec));
doClose(std::move(ec), true);
}

void YamuxStream::doClose(std::error_code ec) {
void YamuxStream::doClose(std::error_code ec, bool keepInternalBuffer) {
// ensure lifetime of this object during doClose
auto self = shared_from_this();

Expand All @@ -323,7 +323,9 @@ namespace libp2p::connection {
is_readable_ = false;
is_writable_ = false;

internal_read_buffer_.clear();
if (!keepInternalBuffer) {
internal_read_buffer_.clear();
}

auto write_callbacks = write_queue_.getAllCallbacks();

Expand Down
126 changes: 126 additions & 0 deletions test/libp2p/muxer/muxers_and_streams_test.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,11 @@
* SPDX-License-Identifier: Apache-2.0
*/

#include <atomic>
#include <chrono>
#include <cstdlib>
#include <iosfwd>
#include <thread>

#include <gtest/gtest.h>
#include <boost/di/extension/scopes/shared.hpp>
Expand Down Expand Up @@ -219,6 +222,14 @@ namespace libp2p::regression {
host_->stop();
}

std::shared_ptr<Bytes> readBuf() {
return read_buf_;
}

std::shared_ptr<Bytes> writeBuf() {
return write_buf_;
}

private:
const Behavior &behavior_;
Stats stats_;
Expand Down Expand Up @@ -516,6 +527,109 @@ void testOutboundConnectionAcceptsStreams(InjectorArgs &&...args) {
}
}

template <typename... InjectorArgs>
void testStreamIsReadableAfterConnectionClosed(InjectorArgs &&...args) {
using namespace libp2p::regression; // NOLINT
constexpr size_t kServerId = 0;
constexpr size_t kClientId = 1;

enum class Steps { Initial = 0, ClientWrote, ServerRead };
std::atomic<Steps> step = Steps::Initial;

auto waitStep = [&step](Steps requiredStep,
std::chrono::seconds time =
std::chrono::seconds(1)) -> bool {
auto start = std::chrono::system_clock::now();
while (step.load() != requiredStep
&& std::chrono::system_clock::now() - start < time) {
std::this_thread::yield();
}
return step.load() == requiredStep;
};

std::shared_ptr<boost::asio::io_context> io;
std::shared_ptr<Node> client;
std::shared_ptr<Node> server;

Node::Behavior server_behavior = [&](Node &node) {
auto stats = node.getStats();
TRACE("Server event: {}", stats.lastEvent());
switch (stats.lastEvent()) {
case Stats::READ:
case Stats::READ_FAILURE: {
step = Steps::ServerRead;
break;
}
default:
break;
}
};

Node::Behavior client_behavior = [&](Node &node) {
auto stats = node.getStats();
TRACE("Client event: {}", stats.lastEvent());
switch (stats.lastEvent()) {
case Stats::CONNECTED:
return node.write();
case Stats::WRITE:
node.stop();
step = Steps::ClientWrote;
break;
default:
break;
}
};

auto listen_to =
libp2p::multi::Multiaddress::create("/ip4/127.0.0.1/tcp/40001").value();

io = std::make_shared<boost::asio::io_context>();

server = std::make_shared<Node>(kServerId,
false,
server_behavior,
io,
std::forward<decltype(args)>(args)...);
client = std::make_shared<Node>(kClientId,
false,
client_behavior,
io,
std::forward<decltype(args)>(args)...);

post(*io, [&]() {
server->listen(listen_to);
libp2p::peer::PeerInfo peer_info{server->getId(), {listen_to}};
client->connect(peer_info);
});
auto f = std::async(std::launch::async, [&]() { runEventLoop(io); });

EXPECT_TRUE(waitStep(Steps::ClientWrote));
EXPECT_EQ(server->getStats().lastEvent(), Stats::ACCEPTED);
std::this_thread::sleep_for(
std::chrono::seconds(1)); // wait connection on server to be closed

server->read();

EXPECT_TRUE(waitStep(Steps::ServerRead));
EXPECT_EQ(server->getStats().lastEvent(), Stats::READ);
auto writtenBuf = client->writeBuf();
EXPECT_TRUE(writtenBuf);
auto readBuf = server->readBuf();
EXPECT_TRUE(readBuf);
if (writtenBuf && readBuf) {
EXPECT_EQ(*writtenBuf, *readBuf);
}

io->stop();

if (server) {
server->stop();
}
if (client) {
client->stop();
}
}

TEST(StreamsRegression, YamuxStreamsGetNotifiedAboutEOF) {
testStreamsGetNotifiedAboutEOF(
false,
Expand Down Expand Up @@ -587,6 +701,18 @@ TEST(StreamsRegression, YamuxNoiseStreamsGetNotifiedAboutEOFJumboMsg) {
libp2p::injector::useSecurityAdaptors<libp2p::security::Noise>());
}

TEST(StreamsRegression, YamuxStreamIsReadableAfterConnectionClosed) {
testStreamIsReadableAfterConnectionClosed(
boost::di::bind<libp2p::muxer::MuxerAdaptor *[]>()
.to<libp2p::muxer::Yamux>()[boost::di::override]);
}

TEST(StreamsRegression, MplexStreamIsReadableAfterConnectionClosed) {
testStreamIsReadableAfterConnectionClosed(
boost::di::bind<libp2p::muxer::MuxerAdaptor *[]>()
.to<libp2p::muxer::Mplex>()[boost::di::override]);
}

int main(int argc, char *argv[]) {
if (std::getenv("TRACE_DEBUG") != nullptr) {
testutil::prepareLoggers(soralog::Level::TRACE);
Expand Down