DHTMessageFactoryImpl.cc 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508
  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. SharedHandle<DHTMessage> DHTMessageFactoryImpl::createQueryMessage
  163. (const BDE& dict,
  164. const std::string& ipaddr,
  165. uint16_t port)
  166. {
  167. const BDE& messageType = getString(dict, DHTQueryMessage::Q);
  168. const BDE& transactionID = getString(dict, DHTMessage::T);
  169. const BDE& y = getString(dict, DHTMessage::Y);
  170. const BDE& aDict = getDictionary(dict, DHTQueryMessage::A);
  171. if(y.s() != DHTQueryMessage::Q) {
  172. throw DL_ABORT_EX("Malformed DHT message. y != q");
  173. }
  174. const BDE& id = getString(aDict, DHTMessage::ID);
  175. validateID(id);
  176. SharedHandle<DHTNode> remoteNode = getRemoteNode(id.uc(), ipaddr, port);
  177. if(messageType.s() == DHTPingMessage::PING) {
  178. return createPingMessage(remoteNode, transactionID.s());
  179. } else if(messageType.s() == DHTFindNodeMessage::FIND_NODE) {
  180. const BDE& targetNodeID =
  181. getString(aDict, DHTFindNodeMessage::TARGET_NODE);
  182. validateID(targetNodeID);
  183. return createFindNodeMessage(remoteNode, targetNodeID.uc(),
  184. transactionID.s());
  185. } else if(messageType.s() == DHTGetPeersMessage::GET_PEERS) {
  186. const BDE& infoHash =
  187. getString(aDict, DHTGetPeersMessage::INFO_HASH);
  188. validateID(infoHash);
  189. return createGetPeersMessage(remoteNode,
  190. infoHash.uc(), transactionID.s());
  191. } else if(messageType.s() == DHTAnnouncePeerMessage::ANNOUNCE_PEER) {
  192. const BDE& infoHash =
  193. getString(aDict, DHTAnnouncePeerMessage::INFO_HASH);
  194. validateID(infoHash);
  195. const BDE& port = getInteger(aDict, DHTAnnouncePeerMessage::PORT);
  196. validatePort(port);
  197. const BDE& token = getString(aDict, DHTAnnouncePeerMessage::TOKEN);
  198. return createAnnouncePeerMessage(remoteNode, infoHash.uc(),
  199. static_cast<uint16_t>(port.i()),
  200. token.s(), transactionID.s());
  201. } else {
  202. throw DL_ABORT_EX
  203. (StringFormat("Unsupported message type: %s",
  204. messageType.s().c_str()).str());
  205. }
  206. }
  207. SharedHandle<DHTMessage>
  208. DHTMessageFactoryImpl::createResponseMessage(const std::string& messageType,
  209. const BDE& dict,
  210. const std::string& ipaddr,
  211. uint16_t port)
  212. {
  213. const BDE& transactionID = getString(dict, DHTMessage::T);
  214. const BDE& y = getString(dict, DHTMessage::Y);
  215. if(y.s() == DHTUnknownMessage::E) {
  216. // for now, just report error message arrived and throw exception.
  217. const BDE& e = getList(dict, DHTUnknownMessage::E);
  218. if(e.size() == 2) {
  219. _logger->info("Received Error DHT message. code=%s, msg=%s",
  220. util::itos(getInteger(e, 0).i()).c_str(),
  221. util::urlencode(getString(e, 1).s()).c_str());
  222. } else {
  223. if(_logger->debug()) {
  224. _logger->debug("e doesn't have 2 elements.");
  225. }
  226. }
  227. throw DL_ABORT_EX("Received Error DHT message.");
  228. } else if(y.s() != DHTResponseMessage::R) {
  229. throw DL_ABORT_EX
  230. (StringFormat("Malformed DHT message. y != r: y=%s",
  231. util::urlencode(y.s()).c_str()).str());
  232. }
  233. const BDE& rDict = getDictionary(dict, DHTResponseMessage::R);
  234. const BDE& id = getString(rDict, DHTMessage::ID);
  235. validateID(id);
  236. SharedHandle<DHTNode> remoteNode = getRemoteNode(id.uc(), ipaddr, port);
  237. if(messageType == DHTPingReplyMessage::PING) {
  238. return createPingReplyMessage(remoteNode, id.uc(), transactionID.s());
  239. } else if(messageType == DHTFindNodeReplyMessage::FIND_NODE) {
  240. return createFindNodeReplyMessage(remoteNode, dict, transactionID.s());
  241. } else if(messageType == DHTGetPeersReplyMessage::GET_PEERS) {
  242. const BDE& valuesList = rDict[DHTGetPeersReplyMessage::VALUES];
  243. if(valuesList.isList()) {
  244. return createGetPeersReplyMessageWithValues(remoteNode, dict,
  245. transactionID.s());
  246. } else {
  247. const BDE& nodes = rDict[DHTGetPeersReplyMessage::NODES];
  248. if(nodes.isString()) {
  249. return createGetPeersReplyMessageWithNodes(remoteNode, dict,
  250. transactionID.s());
  251. } else {
  252. throw DL_ABORT_EX("Malformed DHT message: missing nodes/values");
  253. }
  254. }
  255. } else if(messageType == DHTAnnouncePeerReplyMessage::ANNOUNCE_PEER) {
  256. return createAnnouncePeerReplyMessage(remoteNode, transactionID.s());
  257. } else {
  258. throw DL_ABORT_EX
  259. (StringFormat("Unsupported message type: %s", messageType.c_str()).str());
  260. }
  261. }
  262. void DHTMessageFactoryImpl::setCommonProperty(const SharedHandle<DHTAbstractMessage>& m)
  263. {
  264. m->setConnection(_connection);
  265. m->setMessageDispatcher(_dispatcher);
  266. m->setRoutingTable(_routingTable);
  267. WeakHandle<DHTMessageFactory> factory(this);
  268. m->setMessageFactory(factory);
  269. }
  270. SharedHandle<DHTMessage> DHTMessageFactoryImpl::createPingMessage(const SharedHandle<DHTNode>& remoteNode, const std::string& transactionID)
  271. {
  272. SharedHandle<DHTPingMessage> m(new DHTPingMessage(_localNode, remoteNode, transactionID));
  273. setCommonProperty(m);
  274. return m;
  275. }
  276. SharedHandle<DHTMessage>
  277. DHTMessageFactoryImpl::createPingReplyMessage(const SharedHandle<DHTNode>& remoteNode,
  278. const unsigned char* id,
  279. const std::string& transactionID)
  280. {
  281. SharedHandle<DHTPingReplyMessage> m(new DHTPingReplyMessage(_localNode, remoteNode, id, transactionID));
  282. setCommonProperty(m);
  283. return m;
  284. }
  285. SharedHandle<DHTMessage>
  286. DHTMessageFactoryImpl::createFindNodeMessage(const SharedHandle<DHTNode>& remoteNode,
  287. const unsigned char* targetNodeID,
  288. const std::string& transactionID)
  289. {
  290. SharedHandle<DHTFindNodeMessage> m(new DHTFindNodeMessage(_localNode, remoteNode, targetNodeID, transactionID));
  291. setCommonProperty(m);
  292. return m;
  293. }
  294. SharedHandle<DHTMessage>
  295. DHTMessageFactoryImpl::createFindNodeReplyMessage(const SharedHandle<DHTNode>& remoteNode,
  296. const std::deque<SharedHandle<DHTNode> >& closestKNodes,
  297. const std::string& transactionID)
  298. {
  299. SharedHandle<DHTFindNodeReplyMessage> m(new DHTFindNodeReplyMessage(_localNode, remoteNode, transactionID));
  300. m->setClosestKNodes(closestKNodes);
  301. setCommonProperty(m);
  302. return m;
  303. }
  304. std::deque<SharedHandle<DHTNode> >
  305. DHTMessageFactoryImpl::extractNodes(const unsigned char* src, size_t length)
  306. {
  307. if(length%26 != 0) {
  308. throw DL_ABORT_EX("Nodes length is not multiple of 26");
  309. }
  310. std::deque<SharedHandle<DHTNode> > nodes;
  311. for(size_t offset = 0; offset < length; offset += 26) {
  312. SharedHandle<DHTNode> node(new DHTNode(src+offset));
  313. std::pair<std::string, uint16_t> addr =
  314. bittorrent::unpackcompact(src+offset+DHT_ID_LENGTH);
  315. if(addr.first.empty()) {
  316. continue;
  317. }
  318. node->setIPAddress(addr.first);
  319. node->setPort(addr.second);
  320. nodes.push_back(node);
  321. }
  322. return nodes;
  323. }
  324. SharedHandle<DHTMessage>
  325. DHTMessageFactoryImpl::createFindNodeReplyMessage
  326. (const SharedHandle<DHTNode>& remoteNode,
  327. const BDE& dict,
  328. const std::string& transactionID)
  329. {
  330. const BDE& nodesData =
  331. getString(getDictionary(dict, DHTResponseMessage::R),
  332. DHTFindNodeReplyMessage::NODES);
  333. std::deque<SharedHandle<DHTNode> > nodes = extractNodes(nodesData.uc(),
  334. nodesData.s().size());
  335. return createFindNodeReplyMessage(remoteNode, nodes, transactionID);
  336. }
  337. SharedHandle<DHTMessage>
  338. DHTMessageFactoryImpl::createGetPeersMessage(const SharedHandle<DHTNode>& remoteNode,
  339. const unsigned char* infoHash,
  340. const std::string& transactionID)
  341. {
  342. SharedHandle<DHTGetPeersMessage> m(new DHTGetPeersMessage(_localNode,
  343. remoteNode,
  344. infoHash,
  345. transactionID));
  346. m->setPeerAnnounceStorage(_peerAnnounceStorage);
  347. m->setTokenTracker(_tokenTracker);
  348. setCommonProperty(m);
  349. return m;
  350. }
  351. SharedHandle<DHTMessage>
  352. DHTMessageFactoryImpl::createGetPeersReplyMessageWithNodes
  353. (const SharedHandle<DHTNode>& remoteNode,
  354. const BDE& dict,
  355. const std::string& transactionID)
  356. {
  357. const BDE& rDict = getDictionary(dict, DHTResponseMessage::R);
  358. const BDE& nodesData = getString(rDict,
  359. DHTGetPeersReplyMessage::NODES);
  360. std::deque<SharedHandle<DHTNode> > nodes = extractNodes(nodesData.uc(),
  361. nodesData.s().size());
  362. const BDE& token = getString(rDict, DHTGetPeersReplyMessage::TOKEN);
  363. return createGetPeersReplyMessage(remoteNode, nodes, token.s(),
  364. transactionID);
  365. }
  366. SharedHandle<DHTMessage>
  367. DHTMessageFactoryImpl::createGetPeersReplyMessage(const SharedHandle<DHTNode>& remoteNode,
  368. const std::deque<SharedHandle<DHTNode> >& closestKNodes,
  369. const std::string& token,
  370. const std::string& transactionID)
  371. {
  372. SharedHandle<DHTGetPeersReplyMessage> m
  373. (new DHTGetPeersReplyMessage(_localNode, remoteNode, token, transactionID));
  374. m->setClosestKNodes(closestKNodes);
  375. setCommonProperty(m);
  376. return m;
  377. }
  378. SharedHandle<DHTMessage>
  379. DHTMessageFactoryImpl::createGetPeersReplyMessageWithValues
  380. (const SharedHandle<DHTNode>& remoteNode,
  381. const BDE& dict,
  382. const std::string& transactionID)
  383. {
  384. const BDE& rDict = getDictionary(dict, DHTResponseMessage::R);
  385. const BDE& valuesList = getList(rDict,
  386. DHTGetPeersReplyMessage::VALUES);
  387. std::deque<SharedHandle<Peer> > peers;
  388. for(BDE::List::const_iterator i = valuesList.listBegin();
  389. i != valuesList.listEnd(); ++i) {
  390. const BDE& data = *i;
  391. if(data.isString() && data.s().size() == 6) {
  392. std::pair<std::string, uint16_t> addr =
  393. bittorrent::unpackcompact(data.uc());
  394. PeerHandle peer(new Peer(addr.first, addr.second));
  395. peers.push_back(peer);
  396. }
  397. }
  398. const BDE& token = getString(rDict, DHTGetPeersReplyMessage::TOKEN);
  399. return createGetPeersReplyMessage(remoteNode, peers, token.s(),
  400. transactionID);
  401. }
  402. SharedHandle<DHTMessage>
  403. DHTMessageFactoryImpl::createGetPeersReplyMessage(const SharedHandle<DHTNode>& remoteNode,
  404. const std::deque<SharedHandle<Peer> >& values,
  405. const std::string& token,
  406. const std::string& transactionID)
  407. {
  408. SharedHandle<DHTGetPeersReplyMessage> m(new DHTGetPeersReplyMessage(_localNode, remoteNode, token, transactionID));
  409. m->setValues(values);
  410. setCommonProperty(m);
  411. return m;
  412. }
  413. SharedHandle<DHTMessage>
  414. DHTMessageFactoryImpl::createAnnouncePeerMessage(const SharedHandle<DHTNode>& remoteNode,
  415. const unsigned char* infoHash,
  416. uint16_t tcpPort,
  417. const std::string& token,
  418. const std::string& transactionID)
  419. {
  420. SharedHandle<DHTAnnouncePeerMessage> m
  421. (new DHTAnnouncePeerMessage(_localNode, remoteNode, infoHash, tcpPort, token, transactionID));
  422. m->setPeerAnnounceStorage(_peerAnnounceStorage);
  423. m->setTokenTracker(_tokenTracker);
  424. setCommonProperty(m);
  425. return m;
  426. }
  427. SharedHandle<DHTMessage>
  428. DHTMessageFactoryImpl::createAnnouncePeerReplyMessage(const SharedHandle<DHTNode>& remoteNode,
  429. const std::string& transactionID)
  430. {
  431. SharedHandle<DHTAnnouncePeerReplyMessage> m
  432. (new DHTAnnouncePeerReplyMessage(_localNode, remoteNode, transactionID));
  433. setCommonProperty(m);
  434. return m;
  435. }
  436. SharedHandle<DHTMessage>
  437. DHTMessageFactoryImpl::createUnknownMessage(const unsigned char* data, size_t length,
  438. const std::string& ipaddr, uint16_t port)
  439. {
  440. SharedHandle<DHTUnknownMessage> m
  441. (new DHTUnknownMessage(_localNode, data, length, ipaddr, port));
  442. return m;
  443. }
  444. void DHTMessageFactoryImpl::setRoutingTable(const WeakHandle<DHTRoutingTable>& routingTable)
  445. {
  446. _routingTable = routingTable;
  447. }
  448. void DHTMessageFactoryImpl::setConnection(const WeakHandle<DHTConnection>& connection)
  449. {
  450. _connection = connection;
  451. }
  452. void DHTMessageFactoryImpl::setMessageDispatcher(const WeakHandle<DHTMessageDispatcher>& dispatcher)
  453. {
  454. _dispatcher = dispatcher;
  455. }
  456. void DHTMessageFactoryImpl::setPeerAnnounceStorage(const WeakHandle<DHTPeerAnnounceStorage>& storage)
  457. {
  458. _peerAnnounceStorage = storage;
  459. }
  460. void DHTMessageFactoryImpl::setTokenTracker(const WeakHandle<DHTTokenTracker>& tokenTracker)
  461. {
  462. _tokenTracker = tokenTracker;
  463. }
  464. void DHTMessageFactoryImpl::setLocalNode(const SharedHandle<DHTNode>& localNode)
  465. {
  466. _localNode = localNode;
  467. }
  468. } // namespace aria2