DHTMessageFactoryImpl.cc 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543
  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 "StringFormat.h"
  62. #include "bencode.h"
  63. namespace aria2 {
  64. DHTMessageFactoryImpl::DHTMessageFactoryImpl():
  65. _logger(LogFactory::getInstance()) {}
  66. DHTMessageFactoryImpl::~DHTMessageFactoryImpl() {}
  67. SharedHandle<DHTNode>
  68. DHTMessageFactoryImpl::getRemoteNode(const unsigned char* id, const std::string& ipaddr, uint16_t port) const
  69. {
  70. SharedHandle<DHTNode> node = _routingTable->getNode(id, ipaddr, port);
  71. if(node.isNull()) {
  72. node.reset(new DHTNode(id));
  73. node->setIPAddress(ipaddr);
  74. node->setPort(port);
  75. }
  76. return node;
  77. }
  78. static const BDE& getDictionary(const BDE& dict,
  79. const std::string& key)
  80. {
  81. const BDE& d = dict[key];
  82. if(d.isDict()) {
  83. return d;
  84. } else {
  85. throw DL_ABORT_EX
  86. (StringFormat("Malformed DHT message. Missing %s", key.c_str()).str());
  87. }
  88. }
  89. static const BDE& getString(const BDE& dict,
  90. const std::string& key)
  91. {
  92. const BDE& c = dict[key];
  93. if(c.isString()) {
  94. return c;
  95. } else {
  96. throw DL_ABORT_EX
  97. (StringFormat("Malformed DHT message. Missing %s", key.c_str()).str());
  98. }
  99. }
  100. static const BDE& getInteger(const BDE& dict,
  101. const std::string& key)
  102. {
  103. const BDE& c = dict[key];
  104. if(c.isInteger()) {
  105. return c;
  106. } else {
  107. throw DL_ABORT_EX
  108. (StringFormat("Malformed DHT message. Missing %s", key.c_str()).str());
  109. }
  110. }
  111. static const BDE& getString(const BDE& list, size_t index)
  112. {
  113. const BDE& c = list[index];
  114. if(c.isString()) {
  115. return c;
  116. } else {
  117. throw DL_ABORT_EX
  118. (StringFormat("Malformed DHT message. element[%u] is not String.",
  119. index).str());
  120. }
  121. }
  122. static const BDE& getInteger(const BDE& list, size_t index)
  123. {
  124. const BDE& c = list[index];
  125. if(c.isInteger()) {
  126. return c;
  127. } else {
  128. throw DL_ABORT_EX
  129. (StringFormat("Malformed DHT message. element[%u] is not Integer.",
  130. index).str());
  131. }
  132. }
  133. static const BDE& getList(const BDE& dict,
  134. const std::string& key)
  135. {
  136. const BDE& l = dict[key];
  137. if(l.isList()) {
  138. return l;
  139. } else {
  140. throw DL_ABORT_EX
  141. (StringFormat("Malformed DHT message. Missing %s", key.c_str()).str());
  142. }
  143. }
  144. void DHTMessageFactoryImpl::validateID(const BDE& id) const
  145. {
  146. if(id.s().size() != DHT_ID_LENGTH) {
  147. throw DL_ABORT_EX
  148. (StringFormat("Malformed DHT message. Invalid ID length."
  149. " Expected:%d, Actual:%d",
  150. DHT_ID_LENGTH, id.s().size()).str());
  151. }
  152. }
  153. void DHTMessageFactoryImpl::validatePort(const BDE& i) const
  154. {
  155. BDE::Integer port = i.i();
  156. if(!(0 < port && port < UINT16_MAX)) {
  157. throw DL_ABORT_EX
  158. (StringFormat("Malformed DHT message. Invalid port=%s",
  159. util::itos(port).c_str()).str());
  160. }
  161. }
  162. static void setVersion(const SharedHandle<DHTMessage>& msg, const BDE& dict)
  163. {
  164. const BDE& v = dict[DHTMessage::V];
  165. if(v.isString()) {
  166. msg->setVersion(v.s());
  167. } else {
  168. msg->setVersion(A2STR::NIL);
  169. }
  170. }
  171. SharedHandle<DHTMessage> DHTMessageFactoryImpl::createQueryMessage
  172. (const BDE& dict,
  173. const std::string& ipaddr,
  174. uint16_t port)
  175. {
  176. const BDE& messageType = getString(dict, DHTQueryMessage::Q);
  177. const BDE& transactionID = getString(dict, DHTMessage::T);
  178. const BDE& y = getString(dict, DHTMessage::Y);
  179. const BDE& aDict = getDictionary(dict, DHTQueryMessage::A);
  180. if(y.s() != DHTQueryMessage::Q) {
  181. throw DL_ABORT_EX("Malformed DHT message. y != q");
  182. }
  183. const BDE& id = getString(aDict, DHTMessage::ID);
  184. validateID(id);
  185. SharedHandle<DHTNode> remoteNode = getRemoteNode(id.uc(), ipaddr, port);
  186. SharedHandle<DHTMessage> msg;
  187. if(messageType.s() == DHTPingMessage::PING) {
  188. msg = createPingMessage(remoteNode, transactionID.s());
  189. } else if(messageType.s() == DHTFindNodeMessage::FIND_NODE) {
  190. const BDE& targetNodeID =
  191. getString(aDict, DHTFindNodeMessage::TARGET_NODE);
  192. validateID(targetNodeID);
  193. msg = createFindNodeMessage(remoteNode, targetNodeID.uc(),
  194. transactionID.s());
  195. } else if(messageType.s() == DHTGetPeersMessage::GET_PEERS) {
  196. const BDE& infoHash =
  197. getString(aDict, DHTGetPeersMessage::INFO_HASH);
  198. validateID(infoHash);
  199. msg = createGetPeersMessage(remoteNode,
  200. infoHash.uc(), transactionID.s());
  201. } else if(messageType.s() == DHTAnnouncePeerMessage::ANNOUNCE_PEER) {
  202. const BDE& infoHash =
  203. getString(aDict, DHTAnnouncePeerMessage::INFO_HASH);
  204. validateID(infoHash);
  205. const BDE& port = getInteger(aDict, DHTAnnouncePeerMessage::PORT);
  206. validatePort(port);
  207. const BDE& token = getString(aDict, DHTAnnouncePeerMessage::TOKEN);
  208. msg = createAnnouncePeerMessage(remoteNode, infoHash.uc(),
  209. static_cast<uint16_t>(port.i()),
  210. token.s(), transactionID.s());
  211. } else {
  212. throw DL_ABORT_EX
  213. (StringFormat("Unsupported message type: %s",
  214. messageType.s().c_str()).str());
  215. }
  216. setVersion(msg, dict);
  217. return msg;
  218. }
  219. SharedHandle<DHTMessage>
  220. DHTMessageFactoryImpl::createResponseMessage(const std::string& messageType,
  221. const BDE& dict,
  222. const std::string& ipaddr,
  223. uint16_t port)
  224. {
  225. const BDE& transactionID = getString(dict, DHTMessage::T);
  226. const BDE& y = getString(dict, DHTMessage::Y);
  227. if(y.s() == DHTUnknownMessage::E) {
  228. // for now, just report error message arrived and throw exception.
  229. const BDE& e = getList(dict, DHTUnknownMessage::E);
  230. if(e.size() == 2) {
  231. if(_logger->info()) {
  232. _logger->info("Received Error DHT message. code=%s, msg=%s",
  233. util::itos(getInteger(e, 0).i()).c_str(),
  234. util::percentEncode(getString(e, 1).s()).c_str());
  235. }
  236. } else {
  237. if(_logger->debug()) {
  238. _logger->debug("e doesn't have 2 elements.");
  239. }
  240. }
  241. throw DL_ABORT_EX("Received Error DHT message.");
  242. } else if(y.s() != DHTResponseMessage::R) {
  243. throw DL_ABORT_EX
  244. (StringFormat("Malformed DHT message. y != r: y=%s",
  245. util::percentEncode(y.s()).c_str()).str());
  246. }
  247. const BDE& rDict = getDictionary(dict, DHTResponseMessage::R);
  248. const BDE& id = getString(rDict, DHTMessage::ID);
  249. validateID(id);
  250. SharedHandle<DHTNode> remoteNode = getRemoteNode(id.uc(), ipaddr, port);
  251. SharedHandle<DHTMessage> msg;
  252. if(messageType == DHTPingReplyMessage::PING) {
  253. msg = createPingReplyMessage(remoteNode, id.uc(), transactionID.s());
  254. } else if(messageType == DHTFindNodeReplyMessage::FIND_NODE) {
  255. msg = createFindNodeReplyMessage(remoteNode, dict, transactionID.s());
  256. } else if(messageType == DHTGetPeersReplyMessage::GET_PEERS) {
  257. const BDE& valuesList = rDict[DHTGetPeersReplyMessage::VALUES];
  258. if(valuesList.isList()) {
  259. msg = createGetPeersReplyMessageWithValues(remoteNode, dict,
  260. transactionID.s());
  261. } else {
  262. const BDE& nodes = rDict[DHTGetPeersReplyMessage::NODES];
  263. if(nodes.isString()) {
  264. msg = createGetPeersReplyMessageWithNodes(remoteNode, dict,
  265. transactionID.s());
  266. } else {
  267. throw DL_ABORT_EX("Malformed DHT message: missing nodes/values");
  268. }
  269. }
  270. } else if(messageType == DHTAnnouncePeerReplyMessage::ANNOUNCE_PEER) {
  271. msg = createAnnouncePeerReplyMessage(remoteNode, transactionID.s());
  272. } else {
  273. throw DL_ABORT_EX
  274. (StringFormat("Unsupported message type: %s", messageType.c_str()).str());
  275. }
  276. setVersion(msg, dict);
  277. return msg;
  278. }
  279. static const std::string& getDefaultVersion()
  280. {
  281. static std::string version;
  282. if(version.empty()) {
  283. uint16_t vnum16 = htons(DHT_VERSION);
  284. unsigned char buf[] = { 'A' , '2', 0, 0 };
  285. char* vnump = reinterpret_cast<char*>(&vnum16);
  286. memcpy(buf+2, vnump, 2);
  287. version.assign(&buf[0], &buf[4]);
  288. }
  289. return version;
  290. }
  291. void DHTMessageFactoryImpl::setCommonProperty(const SharedHandle<DHTAbstractMessage>& m)
  292. {
  293. m->setConnection(_connection);
  294. m->setMessageDispatcher(_dispatcher);
  295. m->setRoutingTable(_routingTable);
  296. WeakHandle<DHTMessageFactory> factory(this);
  297. m->setMessageFactory(factory);
  298. m->setVersion(getDefaultVersion());
  299. }
  300. SharedHandle<DHTMessage> DHTMessageFactoryImpl::createPingMessage(const SharedHandle<DHTNode>& remoteNode, const std::string& transactionID)
  301. {
  302. SharedHandle<DHTPingMessage> m(new DHTPingMessage(_localNode, remoteNode, transactionID));
  303. setCommonProperty(m);
  304. return m;
  305. }
  306. SharedHandle<DHTMessage>
  307. DHTMessageFactoryImpl::createPingReplyMessage(const SharedHandle<DHTNode>& remoteNode,
  308. const unsigned char* id,
  309. const std::string& transactionID)
  310. {
  311. SharedHandle<DHTPingReplyMessage> m(new DHTPingReplyMessage(_localNode, remoteNode, id, transactionID));
  312. setCommonProperty(m);
  313. return m;
  314. }
  315. SharedHandle<DHTMessage>
  316. DHTMessageFactoryImpl::createFindNodeMessage(const SharedHandle<DHTNode>& remoteNode,
  317. const unsigned char* targetNodeID,
  318. const std::string& transactionID)
  319. {
  320. SharedHandle<DHTFindNodeMessage> m(new DHTFindNodeMessage(_localNode, remoteNode, targetNodeID, transactionID));
  321. setCommonProperty(m);
  322. return m;
  323. }
  324. SharedHandle<DHTMessage>
  325. DHTMessageFactoryImpl::createFindNodeReplyMessage
  326. (const SharedHandle<DHTNode>& remoteNode,
  327. const std::vector<SharedHandle<DHTNode> >& closestKNodes,
  328. const std::string& transactionID)
  329. {
  330. SharedHandle<DHTFindNodeReplyMessage> m
  331. (new DHTFindNodeReplyMessage(_localNode, remoteNode, transactionID));
  332. m->setClosestKNodes(closestKNodes);
  333. setCommonProperty(m);
  334. return m;
  335. }
  336. std::vector<SharedHandle<DHTNode> >
  337. DHTMessageFactoryImpl::extractNodes(const unsigned char* src, size_t length)
  338. {
  339. if(length%26 != 0) {
  340. throw DL_ABORT_EX("Nodes length is not multiple of 26");
  341. }
  342. std::vector<SharedHandle<DHTNode> > nodes;
  343. for(size_t offset = 0; offset < length; offset += 26) {
  344. SharedHandle<DHTNode> node(new DHTNode(src+offset));
  345. std::pair<std::string, uint16_t> addr =
  346. bittorrent::unpackcompact(src+offset+DHT_ID_LENGTH);
  347. if(addr.first.empty()) {
  348. continue;
  349. }
  350. node->setIPAddress(addr.first);
  351. node->setPort(addr.second);
  352. nodes.push_back(node);
  353. }
  354. return nodes;
  355. }
  356. SharedHandle<DHTMessage>
  357. DHTMessageFactoryImpl::createFindNodeReplyMessage
  358. (const SharedHandle<DHTNode>& remoteNode,
  359. const BDE& dict,
  360. const std::string& transactionID)
  361. {
  362. const BDE& nodesData =
  363. getString(getDictionary(dict, DHTResponseMessage::R),
  364. DHTFindNodeReplyMessage::NODES);
  365. std::vector<SharedHandle<DHTNode> > nodes =
  366. extractNodes(nodesData.uc(), nodesData.s().size());
  367. return createFindNodeReplyMessage(remoteNode, nodes, transactionID);
  368. }
  369. SharedHandle<DHTMessage>
  370. DHTMessageFactoryImpl::createGetPeersMessage(const SharedHandle<DHTNode>& remoteNode,
  371. const unsigned char* infoHash,
  372. const std::string& transactionID)
  373. {
  374. SharedHandle<DHTGetPeersMessage> m(new DHTGetPeersMessage(_localNode,
  375. remoteNode,
  376. infoHash,
  377. transactionID));
  378. m->setPeerAnnounceStorage(_peerAnnounceStorage);
  379. m->setTokenTracker(_tokenTracker);
  380. setCommonProperty(m);
  381. return m;
  382. }
  383. SharedHandle<DHTMessage>
  384. DHTMessageFactoryImpl::createGetPeersReplyMessageWithNodes
  385. (const SharedHandle<DHTNode>& remoteNode,
  386. const BDE& dict,
  387. const std::string& transactionID)
  388. {
  389. const BDE& rDict = getDictionary(dict, DHTResponseMessage::R);
  390. const BDE& nodesData = getString(rDict,
  391. DHTGetPeersReplyMessage::NODES);
  392. std::vector<SharedHandle<DHTNode> > nodes =
  393. extractNodes(nodesData.uc(), nodesData.s().size());
  394. const BDE& token = getString(rDict, DHTGetPeersReplyMessage::TOKEN);
  395. return createGetPeersReplyMessage(remoteNode, nodes, token.s(),
  396. transactionID);
  397. }
  398. SharedHandle<DHTMessage>
  399. DHTMessageFactoryImpl::createGetPeersReplyMessage
  400. (const SharedHandle<DHTNode>& remoteNode,
  401. const std::vector<SharedHandle<DHTNode> >& closestKNodes,
  402. const std::string& token,
  403. const std::string& transactionID)
  404. {
  405. SharedHandle<DHTGetPeersReplyMessage> m
  406. (new DHTGetPeersReplyMessage(_localNode, remoteNode, token, transactionID));
  407. m->setClosestKNodes(closestKNodes);
  408. setCommonProperty(m);
  409. return m;
  410. }
  411. SharedHandle<DHTMessage>
  412. DHTMessageFactoryImpl::createGetPeersReplyMessageWithValues
  413. (const SharedHandle<DHTNode>& remoteNode,
  414. const BDE& dict,
  415. const std::string& transactionID)
  416. {
  417. const BDE& rDict = getDictionary(dict, DHTResponseMessage::R);
  418. const BDE& valuesList = getList(rDict,
  419. DHTGetPeersReplyMessage::VALUES);
  420. std::vector<SharedHandle<Peer> > peers;
  421. for(BDE::List::const_iterator i = valuesList.listBegin(),
  422. eoi = valuesList.listEnd(); i != eoi; ++i) {
  423. const BDE& data = *i;
  424. if(data.isString() && data.s().size() == 6) {
  425. std::pair<std::string, uint16_t> addr =
  426. bittorrent::unpackcompact(data.uc());
  427. SharedHandle<Peer> peer(new Peer(addr.first, addr.second));
  428. peers.push_back(peer);
  429. }
  430. }
  431. const BDE& token = getString(rDict, DHTGetPeersReplyMessage::TOKEN);
  432. return createGetPeersReplyMessage(remoteNode, peers, token.s(),
  433. transactionID);
  434. }
  435. SharedHandle<DHTMessage>
  436. DHTMessageFactoryImpl::createGetPeersReplyMessage
  437. (const SharedHandle<DHTNode>& remoteNode,
  438. const std::vector<SharedHandle<Peer> >& values,
  439. const std::string& token,
  440. const std::string& transactionID)
  441. {
  442. SharedHandle<DHTGetPeersReplyMessage> m(new DHTGetPeersReplyMessage(_localNode, remoteNode, token, transactionID));
  443. m->setValues(values);
  444. setCommonProperty(m);
  445. return m;
  446. }
  447. SharedHandle<DHTMessage>
  448. DHTMessageFactoryImpl::createAnnouncePeerMessage(const SharedHandle<DHTNode>& remoteNode,
  449. const unsigned char* infoHash,
  450. uint16_t tcpPort,
  451. const std::string& token,
  452. const std::string& transactionID)
  453. {
  454. SharedHandle<DHTAnnouncePeerMessage> m
  455. (new DHTAnnouncePeerMessage(_localNode, remoteNode, infoHash, tcpPort, token, transactionID));
  456. m->setPeerAnnounceStorage(_peerAnnounceStorage);
  457. m->setTokenTracker(_tokenTracker);
  458. setCommonProperty(m);
  459. return m;
  460. }
  461. SharedHandle<DHTMessage>
  462. DHTMessageFactoryImpl::createAnnouncePeerReplyMessage(const SharedHandle<DHTNode>& remoteNode,
  463. const std::string& transactionID)
  464. {
  465. SharedHandle<DHTAnnouncePeerReplyMessage> m
  466. (new DHTAnnouncePeerReplyMessage(_localNode, remoteNode, transactionID));
  467. setCommonProperty(m);
  468. return m;
  469. }
  470. SharedHandle<DHTMessage>
  471. DHTMessageFactoryImpl::createUnknownMessage(const unsigned char* data, size_t length,
  472. const std::string& ipaddr, uint16_t port)
  473. {
  474. SharedHandle<DHTUnknownMessage> m
  475. (new DHTUnknownMessage(_localNode, data, length, ipaddr, port));
  476. return m;
  477. }
  478. void DHTMessageFactoryImpl::setRoutingTable(const WeakHandle<DHTRoutingTable>& routingTable)
  479. {
  480. _routingTable = routingTable;
  481. }
  482. void DHTMessageFactoryImpl::setConnection(const WeakHandle<DHTConnection>& connection)
  483. {
  484. _connection = connection;
  485. }
  486. void DHTMessageFactoryImpl::setMessageDispatcher(const WeakHandle<DHTMessageDispatcher>& dispatcher)
  487. {
  488. _dispatcher = dispatcher;
  489. }
  490. void DHTMessageFactoryImpl::setPeerAnnounceStorage(const WeakHandle<DHTPeerAnnounceStorage>& storage)
  491. {
  492. _peerAnnounceStorage = storage;
  493. }
  494. void DHTMessageFactoryImpl::setTokenTracker(const WeakHandle<DHTTokenTracker>& tokenTracker)
  495. {
  496. _tokenTracker = tokenTracker;
  497. }
  498. void DHTMessageFactoryImpl::setLocalNode(const SharedHandle<DHTNode>& localNode)
  499. {
  500. _localNode = localNode;
  501. }
  502. } // namespace aria2