DHTMessageFactoryImpl.cc 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532
  1. /* <!-- copyright */
  2. /*
  3. * aria2 - The high speed download utility
  4. *
  5. * Copyright (C) 2006 Tatsuhiro Tsujikawa
  6. *
  7. * This program is free software; you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License as published by
  9. * the Free Software Foundation; either version 2 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * This program is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with this program; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. *
  21. * In addition, as a special exception, the copyright holders give
  22. * permission to link the code of portions of this program with the
  23. * OpenSSL library under certain conditions as described in each
  24. * individual source file, and distribute linked combinations
  25. * including the two.
  26. * You must obey the GNU General Public License in all respects
  27. * for all of the code used other than OpenSSL. If you modify
  28. * file(s) with this exception, you may extend this exception to your
  29. * version of the file(s), but you are not obligated to do so. If you
  30. * do not wish to do so, delete this exception statement from your
  31. * version. If you delete this exception statement from all source
  32. * files in the program, then also delete it here.
  33. */
  34. /* copyright --> */
  35. #include "DHTMessageFactoryImpl.h"
  36. #include <cstring>
  37. #include <utility>
  38. #include "LogFactory.h"
  39. #include "DlAbortEx.h"
  40. #include "DHTNode.h"
  41. #include "DHTRoutingTable.h"
  42. #include "DHTPingMessage.h"
  43. #include "DHTPingReplyMessage.h"
  44. #include "DHTFindNodeMessage.h"
  45. #include "DHTFindNodeReplyMessage.h"
  46. #include "DHTGetPeersMessage.h"
  47. #include "DHTGetPeersReplyMessage.h"
  48. #include "DHTAnnouncePeerMessage.h"
  49. #include "DHTAnnouncePeerReplyMessage.h"
  50. #include "DHTUnknownMessage.h"
  51. #include "DHTConnection.h"
  52. #include "DHTMessageDispatcher.h"
  53. #include "DHTPeerAnnounceStorage.h"
  54. #include "DHTTokenTracker.h"
  55. #include "DHTMessageCallback.h"
  56. #include "bittorrent_helper.h"
  57. #include "BtRuntime.h"
  58. #include "util.h"
  59. #include "Peer.h"
  60. #include "Logger.h"
  61. #include "fmt.h"
  62. namespace aria2 {
  63. DHTMessageFactoryImpl::DHTMessageFactoryImpl(int family)
  64. : family_{family},
  65. connection_{nullptr},
  66. dispatcher_{nullptr},
  67. routingTable_{nullptr},
  68. peerAnnounceStorage_{nullptr},
  69. tokenTracker_{nullptr}
  70. {
  71. }
  72. std::shared_ptr<DHTNode> DHTMessageFactoryImpl::getRemoteNode(
  73. const unsigned char* id, const std::string& ipaddr, uint16_t port) const
  74. {
  75. auto node = routingTable_->getNode(id, ipaddr, port);
  76. if (!node) {
  77. node = std::make_shared<DHTNode>(id);
  78. node->setIPAddress(ipaddr);
  79. node->setPort(port);
  80. }
  81. return node;
  82. }
  83. namespace {
  84. const Dict* getDictionary(const Dict* dict, const std::string& key)
  85. {
  86. const Dict* d = downcast<Dict>(dict->get(key));
  87. if (d) {
  88. return d;
  89. }
  90. else {
  91. throw DL_ABORT_EX(fmt("Malformed DHT message. Missing %s", key.c_str()));
  92. }
  93. }
  94. } // namespace
  95. namespace {
  96. const String* getString(const Dict* dict, const std::string& key)
  97. {
  98. const String* c = downcast<String>(dict->get(key));
  99. if (c) {
  100. return c;
  101. }
  102. else {
  103. throw DL_ABORT_EX(fmt("Malformed DHT message. Missing %s", key.c_str()));
  104. }
  105. }
  106. } // namespace
  107. namespace {
  108. const Integer* getInteger(const Dict* dict, const std::string& key)
  109. {
  110. const Integer* c = downcast<Integer>(dict->get(key));
  111. if (c) {
  112. return c;
  113. }
  114. else {
  115. throw DL_ABORT_EX(fmt("Malformed DHT message. Missing %s", key.c_str()));
  116. }
  117. }
  118. } // namespace
  119. namespace {
  120. const String* getString(const List* list, size_t index)
  121. {
  122. const String* c = downcast<String>(list->get(index));
  123. if (c) {
  124. return c;
  125. }
  126. else {
  127. throw DL_ABORT_EX(fmt("Malformed DHT message. element[%lu] is not String.",
  128. static_cast<unsigned long>(index)));
  129. }
  130. }
  131. } // namespace
  132. namespace {
  133. const Integer* getInteger(const List* list, size_t index)
  134. {
  135. const Integer* c = downcast<Integer>(list->get(index));
  136. if (c) {
  137. return c;
  138. }
  139. else {
  140. throw DL_ABORT_EX(fmt("Malformed DHT message. element[%lu] is not Integer.",
  141. static_cast<unsigned long>(index)));
  142. }
  143. }
  144. } // namespace
  145. namespace {
  146. const List* getList(const Dict* dict, const std::string& key)
  147. {
  148. const List* l = downcast<List>(dict->get(key));
  149. if (l) {
  150. return l;
  151. }
  152. else {
  153. throw DL_ABORT_EX(fmt("Malformed DHT message. Missing %s", key.c_str()));
  154. }
  155. }
  156. } // namespace
  157. void DHTMessageFactoryImpl::validateID(const String* id) const
  158. {
  159. if (id->s().size() != DHT_ID_LENGTH) {
  160. throw DL_ABORT_EX(fmt("Malformed DHT message. Invalid ID length."
  161. " Expected:%lu, Actual:%lu",
  162. static_cast<unsigned long>(DHT_ID_LENGTH),
  163. static_cast<unsigned long>(id->s().size())));
  164. }
  165. }
  166. void DHTMessageFactoryImpl::validatePort(const Integer* port) const
  167. {
  168. if (!(0 < port->i() && port->i() < UINT16_MAX)) {
  169. throw DL_ABORT_EX(
  170. fmt("Malformed DHT message. Invalid port=%" PRId64 "", port->i()));
  171. }
  172. }
  173. namespace {
  174. void setVersion(DHTMessage* msg, const Dict* dict)
  175. {
  176. const String* v = downcast<String>(dict->get(DHTMessage::V));
  177. if (v) {
  178. msg->setVersion(v->s());
  179. }
  180. else {
  181. msg->setVersion(A2STR::NIL);
  182. }
  183. }
  184. } // namespace
  185. std::unique_ptr<DHTQueryMessage> DHTMessageFactoryImpl::createQueryMessage(
  186. const Dict* dict, const std::string& ipaddr, uint16_t port)
  187. {
  188. const String* messageType = getString(dict, DHTQueryMessage::Q);
  189. const String* transactionID = getString(dict, DHTMessage::T);
  190. const String* y = getString(dict, DHTMessage::Y);
  191. const Dict* aDict = getDictionary(dict, DHTQueryMessage::A);
  192. if (y->s() != DHTQueryMessage::Q) {
  193. throw DL_ABORT_EX("Malformed DHT message. y != q");
  194. }
  195. const String* id = getString(aDict, DHTMessage::ID);
  196. validateID(id);
  197. auto remoteNode = getRemoteNode(id->uc(), ipaddr, port);
  198. auto msg = std::unique_ptr<DHTQueryMessage>{};
  199. if (messageType->s() == DHTPingMessage::PING) {
  200. msg = createPingMessage(remoteNode, transactionID->s());
  201. }
  202. else if (messageType->s() == DHTFindNodeMessage::FIND_NODE) {
  203. const String* targetNodeID =
  204. getString(aDict, DHTFindNodeMessage::TARGET_NODE);
  205. validateID(targetNodeID);
  206. msg = createFindNodeMessage(remoteNode, targetNodeID->uc(),
  207. transactionID->s());
  208. }
  209. else if (messageType->s() == DHTGetPeersMessage::GET_PEERS) {
  210. const String* infoHash = getString(aDict, DHTGetPeersMessage::INFO_HASH);
  211. validateID(infoHash);
  212. msg = createGetPeersMessage(remoteNode, infoHash->uc(), transactionID->s());
  213. }
  214. else if (messageType->s() == DHTAnnouncePeerMessage::ANNOUNCE_PEER) {
  215. const String* infoHash =
  216. getString(aDict, DHTAnnouncePeerMessage::INFO_HASH);
  217. validateID(infoHash);
  218. const Integer* port = getInteger(aDict, DHTAnnouncePeerMessage::PORT);
  219. validatePort(port);
  220. const String* token = getString(aDict, DHTAnnouncePeerMessage::TOKEN);
  221. msg = createAnnouncePeerMessage(remoteNode, infoHash->uc(),
  222. static_cast<uint16_t>(port->i()),
  223. token->s(), transactionID->s());
  224. }
  225. else {
  226. throw DL_ABORT_EX(
  227. fmt("Unsupported message type: %s", messageType->s().c_str()));
  228. }
  229. setVersion(msg.get(), dict);
  230. return msg;
  231. }
  232. std::unique_ptr<DHTResponseMessage>
  233. DHTMessageFactoryImpl::createResponseMessage(const std::string& messageType,
  234. const Dict* dict,
  235. const std::string& ipaddr,
  236. uint16_t port)
  237. {
  238. const String* transactionID = getString(dict, DHTMessage::T);
  239. const String* y = getString(dict, DHTMessage::Y);
  240. if (y->s() == DHTUnknownMessage::E) {
  241. // for now, just report error message arrived and throw exception.
  242. const List* e = getList(dict, DHTUnknownMessage::E);
  243. if (e->size() == 2) {
  244. A2_LOG_INFO(fmt("Received Error DHT message. code=%" PRId64 ", msg=%s",
  245. getInteger(e, 0)->i(),
  246. util::percentEncode(getString(e, 1)->s()).c_str()));
  247. }
  248. else {
  249. A2_LOG_DEBUG("e doesn't have 2 elements.");
  250. }
  251. throw DL_ABORT_EX("Received Error DHT message.");
  252. }
  253. else if (y->s() != DHTResponseMessage::R) {
  254. throw DL_ABORT_EX(fmt("Malformed DHT message. y != r: y=%s",
  255. util::percentEncode(y->s()).c_str()));
  256. }
  257. const Dict* rDict = getDictionary(dict, DHTResponseMessage::R);
  258. const String* id = getString(rDict, DHTMessage::ID);
  259. validateID(id);
  260. auto remoteNode = getRemoteNode(id->uc(), ipaddr, port);
  261. auto msg = std::unique_ptr<DHTResponseMessage>{};
  262. if (messageType == DHTPingReplyMessage::PING) {
  263. msg = createPingReplyMessage(remoteNode, id->uc(), transactionID->s());
  264. }
  265. else if (messageType == DHTFindNodeReplyMessage::FIND_NODE) {
  266. msg = createFindNodeReplyMessage(remoteNode, dict, transactionID->s());
  267. }
  268. else if (messageType == DHTGetPeersReplyMessage::GET_PEERS) {
  269. msg = createGetPeersReplyMessage(remoteNode, dict, transactionID->s());
  270. }
  271. else if (messageType == DHTAnnouncePeerReplyMessage::ANNOUNCE_PEER) {
  272. msg = createAnnouncePeerReplyMessage(remoteNode, transactionID->s());
  273. }
  274. else {
  275. throw DL_ABORT_EX(fmt("Unsupported message type: %s", messageType.c_str()));
  276. }
  277. setVersion(msg.get(), dict);
  278. return msg;
  279. }
  280. namespace {
  281. const std::string& getDefaultVersion()
  282. {
  283. static std::string version;
  284. if (version.empty()) {
  285. uint16_t vnum16 = htons(DHT_VERSION);
  286. unsigned char buf[] = {'A', '2', 0, 0};
  287. char* vnump = reinterpret_cast<char*>(&vnum16);
  288. memcpy(buf + 2, vnump, 2);
  289. version.assign(&buf[0], &buf[4]);
  290. }
  291. return version;
  292. }
  293. } // namespace
  294. void DHTMessageFactoryImpl::setCommonProperty(DHTAbstractMessage* m)
  295. {
  296. m->setConnection(connection_);
  297. m->setMessageDispatcher(dispatcher_);
  298. m->setRoutingTable(routingTable_);
  299. m->setMessageFactory(this);
  300. m->setVersion(getDefaultVersion());
  301. }
  302. std::unique_ptr<DHTPingMessage> DHTMessageFactoryImpl::createPingMessage(
  303. const std::shared_ptr<DHTNode>& remoteNode,
  304. const std::string& transactionID)
  305. {
  306. auto m = make_unique<DHTPingMessage>(localNode_, remoteNode, transactionID);
  307. setCommonProperty(m.get());
  308. return m;
  309. }
  310. std::unique_ptr<DHTPingReplyMessage>
  311. DHTMessageFactoryImpl::createPingReplyMessage(
  312. const std::shared_ptr<DHTNode>& remoteNode, const unsigned char* id,
  313. const std::string& transactionID)
  314. {
  315. auto m = make_unique<DHTPingReplyMessage>(localNode_, remoteNode, id,
  316. transactionID);
  317. setCommonProperty(m.get());
  318. return m;
  319. }
  320. std::unique_ptr<DHTFindNodeMessage>
  321. DHTMessageFactoryImpl::createFindNodeMessage(
  322. const std::shared_ptr<DHTNode>& remoteNode,
  323. const unsigned char* targetNodeID, const std::string& transactionID)
  324. {
  325. auto m = make_unique<DHTFindNodeMessage>(localNode_, remoteNode, targetNodeID,
  326. transactionID);
  327. setCommonProperty(m.get());
  328. return m;
  329. }
  330. std::unique_ptr<DHTFindNodeReplyMessage>
  331. DHTMessageFactoryImpl::createFindNodeReplyMessage(
  332. const std::shared_ptr<DHTNode>& remoteNode,
  333. std::vector<std::shared_ptr<DHTNode>> closestKNodes,
  334. const std::string& transactionID)
  335. {
  336. auto m = make_unique<DHTFindNodeReplyMessage>(family_, localNode_, remoteNode,
  337. transactionID);
  338. m->setClosestKNodes(std::move(closestKNodes));
  339. setCommonProperty(m.get());
  340. return m;
  341. }
  342. void DHTMessageFactoryImpl::extractNodes(
  343. std::vector<std::shared_ptr<DHTNode>>& nodes, const unsigned char* src,
  344. size_t length)
  345. {
  346. int unit = bittorrent::getCompactLength(family_) + 20;
  347. if (length % unit != 0) {
  348. throw DL_ABORT_EX(fmt("Nodes length is not multiple of %d", unit));
  349. }
  350. for (size_t offset = 0; offset < length; offset += unit) {
  351. auto node = std::make_shared<DHTNode>(src + offset);
  352. auto addr =
  353. bittorrent::unpackcompact(src + offset + DHT_ID_LENGTH, family_);
  354. if (addr.first.empty()) {
  355. continue;
  356. }
  357. node->setIPAddress(addr.first);
  358. node->setPort(addr.second);
  359. nodes.push_back(std::move(node));
  360. }
  361. }
  362. std::unique_ptr<DHTFindNodeReplyMessage>
  363. DHTMessageFactoryImpl::createFindNodeReplyMessage(
  364. const std::shared_ptr<DHTNode>& remoteNode, const Dict* dict,
  365. const std::string& transactionID)
  366. {
  367. const String* nodesData = downcast<String>(
  368. getDictionary(dict, DHTResponseMessage::R)
  369. ->get(family_ == AF_INET ? DHTFindNodeReplyMessage::NODES
  370. : DHTFindNodeReplyMessage::NODES6));
  371. std::vector<std::shared_ptr<DHTNode>> nodes;
  372. if (nodesData) {
  373. extractNodes(nodes, nodesData->uc(), nodesData->s().size());
  374. }
  375. return createFindNodeReplyMessage(remoteNode, std::move(nodes),
  376. transactionID);
  377. }
  378. std::unique_ptr<DHTGetPeersMessage>
  379. DHTMessageFactoryImpl::createGetPeersMessage(
  380. const std::shared_ptr<DHTNode>& remoteNode, const unsigned char* infoHash,
  381. const std::string& transactionID)
  382. {
  383. auto m = make_unique<DHTGetPeersMessage>(localNode_, remoteNode, infoHash,
  384. transactionID);
  385. m->setPeerAnnounceStorage(peerAnnounceStorage_);
  386. m->setTokenTracker(tokenTracker_);
  387. setCommonProperty(m.get());
  388. return m;
  389. }
  390. std::unique_ptr<DHTGetPeersReplyMessage>
  391. DHTMessageFactoryImpl::createGetPeersReplyMessage(
  392. const std::shared_ptr<DHTNode>& remoteNode, const Dict* dict,
  393. const std::string& transactionID)
  394. {
  395. const Dict* rDict = getDictionary(dict, DHTResponseMessage::R);
  396. const String* nodesData = downcast<String>(
  397. rDict->get(family_ == AF_INET ? DHTGetPeersReplyMessage::NODES
  398. : DHTGetPeersReplyMessage::NODES6));
  399. std::vector<std::shared_ptr<DHTNode>> nodes;
  400. if (nodesData) {
  401. extractNodes(nodes, nodesData->uc(), nodesData->s().size());
  402. }
  403. const List* valuesList =
  404. downcast<List>(rDict->get(DHTGetPeersReplyMessage::VALUES));
  405. std::vector<std::shared_ptr<Peer>> peers;
  406. size_t clen = bittorrent::getCompactLength(family_);
  407. if (valuesList) {
  408. for (auto& elem : *valuesList) {
  409. const String* data = downcast<String>(elem);
  410. if (data && data->s().size() == clen) {
  411. auto addr = bittorrent::unpackcompact(data->uc(), family_);
  412. if (addr.first.empty()) {
  413. continue;
  414. }
  415. peers.push_back(std::make_shared<Peer>(addr.first, addr.second));
  416. }
  417. }
  418. }
  419. const String* token = getString(rDict, DHTGetPeersReplyMessage::TOKEN);
  420. return createGetPeersReplyMessage(remoteNode, std::move(nodes),
  421. std::move(peers), token->s(),
  422. transactionID);
  423. }
  424. std::unique_ptr<DHTGetPeersReplyMessage>
  425. DHTMessageFactoryImpl::createGetPeersReplyMessage(
  426. const std::shared_ptr<DHTNode>& remoteNode,
  427. std::vector<std::shared_ptr<DHTNode>> closestKNodes,
  428. std::vector<std::shared_ptr<Peer>> values, const std::string& token,
  429. const std::string& transactionID)
  430. {
  431. auto m = make_unique<DHTGetPeersReplyMessage>(family_, localNode_, remoteNode,
  432. token, transactionID);
  433. m->setClosestKNodes(std::move(closestKNodes));
  434. m->setValues(std::move(values));
  435. setCommonProperty(m.get());
  436. return m;
  437. }
  438. std::unique_ptr<DHTAnnouncePeerMessage>
  439. DHTMessageFactoryImpl::createAnnouncePeerMessage(
  440. const std::shared_ptr<DHTNode>& remoteNode, const unsigned char* infoHash,
  441. uint16_t tcpPort, const std::string& token,
  442. const std::string& transactionID)
  443. {
  444. auto m = make_unique<DHTAnnouncePeerMessage>(localNode_, remoteNode, infoHash,
  445. tcpPort, token, transactionID);
  446. m->setPeerAnnounceStorage(peerAnnounceStorage_);
  447. m->setTokenTracker(tokenTracker_);
  448. setCommonProperty(m.get());
  449. return m;
  450. }
  451. std::unique_ptr<DHTAnnouncePeerReplyMessage>
  452. DHTMessageFactoryImpl::createAnnouncePeerReplyMessage(
  453. const std::shared_ptr<DHTNode>& remoteNode,
  454. const std::string& transactionID)
  455. {
  456. auto m = make_unique<DHTAnnouncePeerReplyMessage>(localNode_, remoteNode,
  457. transactionID);
  458. setCommonProperty(m.get());
  459. return m;
  460. }
  461. std::unique_ptr<DHTUnknownMessage> DHTMessageFactoryImpl::createUnknownMessage(
  462. const unsigned char* data, size_t length, const std::string& ipaddr,
  463. uint16_t port)
  464. {
  465. return make_unique<DHTUnknownMessage>(localNode_, data, length, ipaddr, port);
  466. }
  467. void DHTMessageFactoryImpl::setRoutingTable(DHTRoutingTable* routingTable)
  468. {
  469. routingTable_ = routingTable;
  470. }
  471. void DHTMessageFactoryImpl::setConnection(DHTConnection* connection)
  472. {
  473. connection_ = connection;
  474. }
  475. void DHTMessageFactoryImpl::setMessageDispatcher(
  476. DHTMessageDispatcher* dispatcher)
  477. {
  478. dispatcher_ = dispatcher;
  479. }
  480. void DHTMessageFactoryImpl::setPeerAnnounceStorage(
  481. DHTPeerAnnounceStorage* storage)
  482. {
  483. peerAnnounceStorage_ = storage;
  484. }
  485. void DHTMessageFactoryImpl::setTokenTracker(DHTTokenTracker* tokenTracker)
  486. {
  487. tokenTracker_ = tokenTracker;
  488. }
  489. void DHTMessageFactoryImpl::setLocalNode(
  490. const std::shared_ptr<DHTNode>& localNode)
  491. {
  492. localNode_ = localNode;
  493. }
  494. } // namespace aria2