diff --git a/src/DHTMessageFactoryImpl.cc b/src/DHTMessageFactoryImpl.cc index 339941332..6d76115e6 100644 --- a/src/DHTMessageFactoryImpl.cc +++ b/src/DHTMessageFactoryImpl.cc @@ -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); } diff --git a/src/DHTPeerLookupTask.cc b/src/DHTPeerLookupTask.cc index 389f4da4a..6724b26e9 100644 --- a/src/DHTPeerLookupTask.cc +++ b/src/DHTPeerLookupTask.cc @@ -75,8 +75,10 @@ void DHTPeerLookupTask::onReceivedInternal( const DHTGetPeersReplyMessage* message) { std::shared_ptr 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(message->getValues().size()))); @@ -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; } } diff --git a/test/DHTMessageFactoryImplTest.cc b/test/DHTMessageFactoryImplTest.cc index 5914b414e..91829ad63 100644 --- a/test/DHTMessageFactoryImplTest.cc +++ b/test/DHTMessageFactoryImplTest.cc @@ -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); @@ -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(); @@ -402,6 +409,89 @@ void DHTMessageFactoryImplTest::testCreateGetPeersReplyMessage6() } } +void DHTMessageFactoryImplTest::checkGetPeersReplyWithoutToken(int family) +{ + factory = make_unique(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(node->getID()), + DHT_ID_LENGTH) + + std::string(reinterpret_cast(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(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(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 { diff --git a/test/DHTPeerLookupTaskTest.cc b/test/DHTPeerLookupTaskTest.cc new file mode 100644 index 000000000..90c057a03 --- /dev/null +++ b/test/DHTPeerLookupTaskTest.cc @@ -0,0 +1,149 @@ +#include "DHTPeerLookupTask.h" + +#include + +#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(); + auto remote = std::make_shared(); + 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(); + attrs->infoHash = std::string(DHT_ID_LENGTH, 'a'); + auto context = std::make_shared(); + 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()); + task.startup(); + CPPUNIT_ASSERT_EQUAL(size_t(1), dispatcher.messageQueue_.size()); + CPPUNIT_ASSERT(dynamic_cast( + 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( + dispatcher.messageQueue_.front().message_.get()); + CPPUNIT_ASSERT(announce); + auto wire = bencode2::decode(announce->getBencodedMessage()); + auto args = downcast(downcast(wire)->get("a")); + CPPUNIT_ASSERT_EQUAL(token, downcast(args->get("token"))->s()); + CPPUNIT_ASSERT(*remote == *announce->getRemoteNode()); + } + } + } +} + +void DHTPeerLookupTaskTest::testTokenlessReplyContinuesLookup() +{ + for (auto family : {AF_INET, AF_INET6}) { + auto local = std::make_shared(); + auto router = std::make_shared(); + router->setIPAddress(family == AF_INET ? "192.0.2.1" : "2001:db8::1"); + router->setPort(6881); + auto next = std::make_shared(); + 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(); + attrs->infoHash = std::string(DHT_ID_LENGTH, 'a'); + auto context = std::make_shared(); + 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()); + 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(next->getID()), + DHT_ID_LENGTH) + + std::string(reinterpret_cast(compact), len)); + dict.put("r", std::move(response)); + auto reply = factory.createResponseMessage( + "get_peers", &dict, router->getIPAddress(), router->getPort()); + auto getPeers = dynamic_cast(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( + 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( + dispatcher.messageQueue_.front().message_.get()); + CPPUNIT_ASSERT(announce); + CPPUNIT_ASSERT(*next == *announce->getRemoteNode()); + CPPUNIT_ASSERT_EQUAL(std::string("token"), announce->getToken()); + } +} + +} // namespace aria2 diff --git a/test/Makefile.am b/test/Makefile.am index af85a649b..1c4a6564b 100644 --- a/test/Makefile.am +++ b/test/Makefile.am @@ -200,6 +200,7 @@ aria2c_SOURCES += BtAllowedFastMessageTest.cc\ DHTAnnouncePeerReplyMessageTest.cc\ DHTUnknownMessageTest.cc\ DHTMessageFactoryImplTest.cc\ + DHTPeerLookupTaskTest.cc\ DHTBucketTreeTest.cc\ DHTPeerAnnounceEntryTest.cc\ DHTPeerAnnounceStorageTest.cc\