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
9 changes: 7 additions & 2 deletions src/DHTMessageFactoryImpl.cc
Original file line number Diff line number Diff line change
Expand Up @@ -445,9 +445,14 @@ DHTMessageFactoryImpl::createGetPeersReplyMessage(
}
}
}
const String* token = getString(rDict, DHTGetPeersReplyMessage::TOKEN);
// Bootstrap routers can return nodes without an announce token. Such a
// response is useful for traversal, but not for announcing ourselves.
// An explicitly supplied token must still be a string.
const String* token = rDict->containsKey(DHTGetPeersReplyMessage::TOKEN)
? getString(rDict, DHTGetPeersReplyMessage::TOKEN)
: nullptr;
return createGetPeersReplyMessage(remoteNode, std::move(nodes),
std::move(peers), token->s(),
std::move(peers), token ? token->s() : "",
transactionID);
}

Expand Down
14 changes: 8 additions & 6 deletions src/DHTPeerLookupTask.cc
Original file line number Diff line number Diff line change
Expand Up @@ -75,8 +75,10 @@ void DHTPeerLookupTask::onReceivedInternal(
const DHTGetPeersReplyMessage* message)
{
std::shared_ptr<DHTNode> remoteNode = message->getRemoteNode();
tokenStorage_[util::toHex(remoteNode->getID(), DHT_ID_LENGTH)] =
message->getToken();
if (!message->getToken().empty()) {
tokenStorage_[util::toHex(remoteNode->getID(), DHT_ID_LENGTH)] =
message->getToken();
}
peerStorage_->addPeer(message->getValues());
A2_LOG_INFO(fmt("Received %lu peers.",
static_cast<unsigned long>(message->getValues().size())));
Expand Down Expand Up @@ -106,16 +108,16 @@ void DHTPeerLookupTask::onFinish()
}
auto& node = (*i)->node;
std::string idHex = util::toHex(node->getID(), DHT_ID_LENGTH);
std::string token = tokenStorage_[idHex];
if (token.empty()) {
A2_LOG_DEBUG(fmt("Token is empty for ID:%s", idHex.c_str()));
auto token = tokenStorage_.find(idHex);
if (token == tokenStorage_.end() || token->second.empty()) {
A2_LOG_DEBUG(fmt("No announce token for ID:%s", idHex.c_str()));
continue;
}
getMessageDispatcher()->addMessageToQueue(
getMessageFactory()->createAnnouncePeerMessage(
node,
getTargetID(), // this is infoHash
tcpPort_, token));
tcpPort_, token->second));
--num;
}
}
Expand Down
90 changes: 90 additions & 0 deletions test/DHTMessageFactoryImplTest.cc
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,9 @@ class DHTMessageFactoryImplTest : public CppUnit::TestFixture {
CPPUNIT_TEST(testCreateGetPeersMessage);
CPPUNIT_TEST(testCreateGetPeersReplyMessage);
CPPUNIT_TEST(testCreateGetPeersReplyMessage6);
CPPUNIT_TEST(testCreateGetPeersReplyMessageWithoutToken);
CPPUNIT_TEST(testCreateGetPeersReplyMessageWithoutToken6);
CPPUNIT_TEST(testCreateGetPeersReplyMessageMalformed);
CPPUNIT_TEST(testCreateAnnouncePeerMessage);
CPPUNIT_TEST(testCreateAnnouncePeerReplyMessage);
CPPUNIT_TEST(testReceivedErrorMessage);
Expand Down Expand Up @@ -83,6 +86,10 @@ class DHTMessageFactoryImplTest : public CppUnit::TestFixture {
void testCreateGetPeersMessage();
void testCreateGetPeersReplyMessage();
void testCreateGetPeersReplyMessage6();
void testCreateGetPeersReplyMessageWithoutToken();
void testCreateGetPeersReplyMessageWithoutToken6();
void testCreateGetPeersReplyMessageMalformed();
void checkGetPeersReplyWithoutToken(int family);
void testCreateAnnouncePeerMessage();
void testCreateAnnouncePeerReplyMessage();
void testReceivedErrorMessage();
Expand Down Expand Up @@ -402,6 +409,89 @@ void DHTMessageFactoryImplTest::testCreateGetPeersReplyMessage6()
}
}

void DHTMessageFactoryImplTest::checkGetPeersReplyWithoutToken(int family)
{
factory = make_unique<DHTMessageFactoryImpl>(family);
factory->setLocalNode(localNode);
factory->setRoutingTable(routingTable.get());
auto node = family == AF_INET ? remoteNode_.get() : remoteNode6_.get();
unsigned char compact[COMPACT_LEN_IPV6];
auto len = bittorrent::packcompact(compact, node->getIPAddress(),
node->getPort());
auto nodes = std::string(reinterpret_cast<const char*>(node->getID()),
DHT_ID_LENGTH) +
std::string(reinterpret_cast<const char*>(compact), len);
Dict dict;
dict.put("t", String::g(transactionID, DHT_TRANSACTION_ID_LENGTH));
dict.put("y", "r");
auto reply = Dict::g();
reply->put("id", String::g(remoteNodeID, DHT_ID_LENGTH));
reply->put(family == AF_INET ? "nodes" : "nodes6", nodes);
dict.put("r", std::move(reply));

auto response = factory->createResponseMessage(
"get_peers", &dict, node->getIPAddress(), node->getPort());
auto message = dynamic_cast<DHTGetPeersReplyMessage*>(response.get());
CPPUNIT_ASSERT(message);
CPPUNIT_ASSERT(message->getToken().empty());
CPPUNIT_ASSERT_EQUAL(size_t(1), message->getClosestKNodes().size());
CPPUNIT_ASSERT(*node == *message->getClosestKNodes().front());
CPPUNIT_ASSERT(message->getValues().empty());
CPPUNIT_ASSERT_EQUAL(util::toHex(transactionID, DHT_TRANSACTION_ID_LENGTH),
util::toHex(message->getTransactionID()));
}

void DHTMessageFactoryImplTest::testCreateGetPeersReplyMessageWithoutToken()
{
checkGetPeersReplyWithoutToken(AF_INET);
}

void DHTMessageFactoryImplTest::testCreateGetPeersReplyMessageWithoutToken6()
{
checkGetPeersReplyWithoutToken(AF_INET6);
}

void DHTMessageFactoryImplTest::testCreateGetPeersReplyMessageMalformed()
{
for (auto family : {AF_INET, AF_INET6}) {
factory = make_unique<DHTMessageFactoryImpl>(family);
factory->setLocalNode(localNode);
factory->setRoutingTable(routingTable.get());
auto node = family == AF_INET ? remoteNode_.get() : remoteNode6_.get();
auto nodesKey = family == AF_INET ? "nodes" : "nodes6";
for (int variant = 0; variant < 6; ++variant) {
Dict dict;
dict.put("t", String::g(transactionID, DHT_TRANSACTION_ID_LENGTH));
dict.put("y", "r");
auto reply = Dict::g();
reply->put("id", String::g(remoteNodeID, DHT_ID_LENGTH));
reply->put(nodesKey, "");
// All malformed cases have no token, except the wrong-type token cases.
if (variant == 0) {
reply->put("token", Integer::g(1));
}
else if (variant == 1) {
reply->put("token", List::g());
}
else if (variant == 2) {
reply->removeKey("id");
}
else if (variant == 3) {
reply->put("id", std::string(DHT_ID_LENGTH - 1, 'x'));
}
else {
auto len = DHT_ID_LENGTH + bittorrent::getCompactLength(family);
reply->put(nodesKey, std::string(variant == 4 ? len - 1 : len + 1, 'x'));
}
dict.put("r", std::move(reply));
CPPUNIT_ASSERT_THROW(factory->createResponseMessage(
"get_peers", &dict, node->getIPAddress(),
node->getPort()),
RecoverableException);
}
}
}

void DHTMessageFactoryImplTest::testCreateAnnouncePeerMessage()
{
try {
Expand Down
149 changes: 149 additions & 0 deletions test/DHTPeerLookupTaskTest.cc
Original file line number Diff line number Diff line change
@@ -0,0 +1,149 @@
#include "DHTPeerLookupTask.h"

#include <cppunit/extensions/HelperMacros.h>

#include "DHTAnnouncePeerMessage.h"
#include "DHTGetPeersMessage.h"
#include "DHTGetPeersReplyMessage.h"
#include "DHTMessageFactoryImpl.h"
#include "DHTNode.h"
#include "DHTRoutingTable.h"
#include "DefaultPeerStorage.h"
#include "DownloadContext.h"
#include "MockDHTMessageDispatcher.h"
#include "TorrentAttribute.h"
#include "bencode2.h"
#include "bittorrent_helper.h"

namespace aria2 {

class DHTPeerLookupTaskTest : public CppUnit::TestFixture {
CPPUNIT_TEST_SUITE(DHTPeerLookupTaskTest);
CPPUNIT_TEST(testAnnounceRequiresToken);
CPPUNIT_TEST(testTokenlessReplyContinuesLookup);
CPPUNIT_TEST_SUITE_END();

public:
void testAnnounceRequiresToken();
void testTokenlessReplyContinuesLookup();
};

CPPUNIT_TEST_SUITE_REGISTRATION(DHTPeerLookupTaskTest);

void DHTPeerLookupTaskTest::testAnnounceRequiresToken()
{
for (auto family : {AF_INET, AF_INET6}) {
for (auto token : {std::string(), std::string("write-token")}) {
auto local = std::make_shared<DHTNode>();
auto remote = std::make_shared<DHTNode>();
remote->setIPAddress(family == AF_INET ? "192.0.2.1" : "2001:db8::1");
remote->setPort(6881);
DHTRoutingTable table(local);
table.addNode(remote);
DHTMessageFactoryImpl factory(family);
factory.setLocalNode(local);
factory.setRoutingTable(&table);
MockDHTMessageDispatcher dispatcher;
auto attrs = std::make_shared<TorrentAttribute>();
attrs->infoHash = std::string(DHT_ID_LENGTH, 'a');
auto context = std::make_shared<DownloadContext>();
context->setAttribute(CTX_ATTR_BT, attrs);
DHTPeerLookupTask task(context, 6881);
task.setLocalNode(local);
task.setRoutingTable(&table);
task.setMessageFactory(&factory);
task.setMessageDispatcher(&dispatcher);
task.setPeerStorage(std::make_shared<DefaultPeerStorage>());
task.startup();
CPPUNIT_ASSERT_EQUAL(size_t(1), dispatcher.messageQueue_.size());
CPPUNIT_ASSERT(dynamic_cast<DHTGetPeersMessage*>(
dispatcher.messageQueue_.front().message_.get()));
dispatcher.messageQueue_.clear();

auto reply = factory.createGetPeersReplyMessage(remote, {}, {}, token, "tx");
task.onReceived(reply.get());
CPPUNIT_ASSERT(task.finished());
CPPUNIT_ASSERT_EQUAL(token.empty() ? size_t(0) : size_t(1),
dispatcher.messageQueue_.size());
if (!token.empty()) {
auto announce = dynamic_cast<DHTAnnouncePeerMessage*>(
dispatcher.messageQueue_.front().message_.get());
CPPUNIT_ASSERT(announce);
auto wire = bencode2::decode(announce->getBencodedMessage());
auto args = downcast<Dict>(downcast<Dict>(wire)->get("a"));
CPPUNIT_ASSERT_EQUAL(token, downcast<String>(args->get("token"))->s());
CPPUNIT_ASSERT(*remote == *announce->getRemoteNode());
}
}
}
}

void DHTPeerLookupTaskTest::testTokenlessReplyContinuesLookup()
{
for (auto family : {AF_INET, AF_INET6}) {
auto local = std::make_shared<DHTNode>();
auto router = std::make_shared<DHTNode>();
router->setIPAddress(family == AF_INET ? "192.0.2.1" : "2001:db8::1");
router->setPort(6881);
auto next = std::make_shared<DHTNode>();
next->setIPAddress(family == AF_INET ? "192.0.2.2" : "2001:db8::2");
next->setPort(6882);
DHTRoutingTable table(local);
table.addNode(router);
DHTMessageFactoryImpl factory(family);
factory.setLocalNode(local);
factory.setRoutingTable(&table);
MockDHTMessageDispatcher dispatcher;
auto attrs = std::make_shared<TorrentAttribute>();
attrs->infoHash = std::string(DHT_ID_LENGTH, 'a');
auto context = std::make_shared<DownloadContext>();
context->setAttribute(CTX_ATTR_BT, attrs);
DHTPeerLookupTask task(context, 6881);
task.setLocalNode(local);
task.setRoutingTable(&table);
task.setMessageFactory(&factory);
task.setMessageDispatcher(&dispatcher);
task.setPeerStorage(std::make_shared<DefaultPeerStorage>());
task.startup();
CPPUNIT_ASSERT_EQUAL(size_t(1), dispatcher.messageQueue_.size());
dispatcher.messageQueue_.clear();

unsigned char compact[COMPACT_LEN_IPV6];
auto len = bittorrent::packcompact(compact, next->getIPAddress(),
next->getPort());
Dict dict;
dict.put("t", "tx");
dict.put("y", "r");
auto response = Dict::g();
response->put("id", String::g(router->getID(), DHT_ID_LENGTH));
response->put(family == AF_INET ? "nodes" : "nodes6",
std::string(reinterpret_cast<const char*>(next->getID()),
DHT_ID_LENGTH) +
std::string(reinterpret_cast<const char*>(compact), len));
dict.put("r", std::move(response));
auto reply = factory.createResponseMessage(
"get_peers", &dict, router->getIPAddress(), router->getPort());
auto getPeers = dynamic_cast<DHTGetPeersReplyMessage*>(reply.get());
CPPUNIT_ASSERT(getPeers);
task.onReceived(getPeers);
CPPUNIT_ASSERT(!task.finished());
CPPUNIT_ASSERT_EQUAL(size_t(1), dispatcher.messageQueue_.size());
auto query = dynamic_cast<DHTGetPeersMessage*>(
dispatcher.messageQueue_.front().message_.get());
CPPUNIT_ASSERT(query);
CPPUNIT_ASSERT(*next == *query->getRemoteNode());
dispatcher.messageQueue_.clear();

auto nextReply = factory.createGetPeersReplyMessage(next, {}, {}, "token", "tx");
task.onReceived(nextReply.get());
CPPUNIT_ASSERT(task.finished());
CPPUNIT_ASSERT_EQUAL(size_t(1), dispatcher.messageQueue_.size());
auto announce = dynamic_cast<DHTAnnouncePeerMessage*>(
dispatcher.messageQueue_.front().message_.get());
CPPUNIT_ASSERT(announce);
CPPUNIT_ASSERT(*next == *announce->getRemoteNode());
CPPUNIT_ASSERT_EQUAL(std::string("token"), announce->getToken());
}
}

} // namespace aria2
1 change: 1 addition & 0 deletions test/Makefile.am
Original file line number Diff line number Diff line change
Expand Up @@ -200,6 +200,7 @@ aria2c_SOURCES += BtAllowedFastMessageTest.cc\
DHTAnnouncePeerReplyMessageTest.cc\
DHTUnknownMessageTest.cc\
DHTMessageFactoryImplTest.cc\
DHTPeerLookupTaskTest.cc\
DHTBucketTreeTest.cc\
DHTPeerAnnounceEntryTest.cc\
DHTPeerAnnounceStorageTest.cc\
Expand Down
Loading