DHTMessageFactoryImpl.cc 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506
  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 "PeerMessageUtil.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 bencode::BDE& getDictionary(const bencode::BDE& dict,
  79. const std::string& key)
  80. {
  81. const bencode::BDE& d = dict[key];
  82. if(d.isDict()) {
  83. return d;
  84. } else {
  85. throw DlAbortEx
  86. (StringFormat("Malformed DHT message. Missing %s", key.c_str()).str());
  87. }
  88. }
  89. static const bencode::BDE& getString(const bencode::BDE& dict,
  90. const std::string& key)
  91. {
  92. const bencode::BDE& c = dict[key];
  93. if(c.isString()) {
  94. return c;
  95. } else {
  96. throw DlAbortEx
  97. (StringFormat("Malformed DHT message. Missing %s", key.c_str()).str());
  98. }
  99. }
  100. static const bencode::BDE& getInteger(const bencode::BDE& dict,
  101. const std::string& key)
  102. {
  103. const bencode::BDE& c = dict[key];
  104. if(c.isInteger()) {
  105. return c;
  106. } else {
  107. throw DlAbortEx
  108. (StringFormat("Malformed DHT message. Missing %s", key.c_str()).str());
  109. }
  110. }
  111. static const bencode::BDE& getString(const bencode::BDE& list, size_t index)
  112. {
  113. const bencode::BDE& c = list[index];
  114. if(c.isString()) {
  115. return c;
  116. } else {
  117. throw DlAbortEx
  118. (StringFormat("Malformed DHT message. element[%u] is not String.",
  119. index).str());
  120. }
  121. }
  122. static const bencode::BDE& getInteger(const bencode::BDE& list, size_t index)
  123. {
  124. const bencode::BDE& c = list[index];
  125. if(c.isInteger()) {
  126. return c;
  127. } else {
  128. throw DlAbortEx
  129. (StringFormat("Malformed DHT message. element[%u] is not Integer.",
  130. index).str());
  131. }
  132. }
  133. static const bencode::BDE& getList(const bencode::BDE& dict,
  134. const std::string& key)
  135. {
  136. const bencode::BDE& l = dict[key];
  137. if(l.isList()) {
  138. return l;
  139. } else {
  140. throw DlAbortEx
  141. (StringFormat("Malformed DHT message. Missing %s", key.c_str()).str());
  142. }
  143. }
  144. void DHTMessageFactoryImpl::validateID(const bencode::BDE& id) const
  145. {
  146. if(id.s().size() != DHT_ID_LENGTH) {
  147. throw DlAbortEx
  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 bencode::BDE& i) const
  154. {
  155. bencode::BDE::Integer port = i.i();
  156. if(!(0 < port && port < UINT16_MAX)) {
  157. throw DlAbortEx
  158. (StringFormat("Malformed DHT message. Invalid port=%s",
  159. Util::itos(port).c_str()).str());
  160. }
  161. }
  162. SharedHandle<DHTMessage> DHTMessageFactoryImpl::createQueryMessage
  163. (const bencode::BDE& dict,
  164. const std::string& ipaddr,
  165. uint16_t port)
  166. {
  167. const bencode::BDE& messageType = getString(dict, DHTQueryMessage::Q);
  168. const bencode::BDE& transactionID = getString(dict, DHTMessage::T);
  169. const bencode::BDE& y = getString(dict, DHTMessage::Y);
  170. const bencode::BDE& aDict = getDictionary(dict, DHTQueryMessage::A);
  171. if(y.s() != DHTQueryMessage::Q) {
  172. throw DlAbortEx("Malformed DHT message. y != q");
  173. }
  174. const bencode::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 bencode::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 bencode::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 bencode::BDE& infoHash =
  193. getString(aDict, DHTAnnouncePeerMessage::INFO_HASH);
  194. validateID(infoHash);
  195. const bencode::BDE& port = getInteger(aDict, DHTAnnouncePeerMessage::PORT);
  196. validatePort(port);
  197. const bencode::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 DlAbortEx
  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 bencode::BDE& dict,
  210. const std::string& ipaddr,
  211. uint16_t port)
  212. {
  213. const bencode::BDE& transactionID = getString(dict, DHTMessage::T);
  214. const bencode::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 bencode::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. _logger->debug("e doesn't have 2 elements.");
  224. }
  225. throw DlAbortEx("Received Error DHT message.");
  226. } else if(y.s() != DHTResponseMessage::R) {
  227. throw DlAbortEx
  228. (StringFormat("Malformed DHT message. y != r: y=%s",
  229. Util::urlencode(y.s()).c_str()).str());
  230. }
  231. const bencode::BDE& rDict = getDictionary(dict, DHTResponseMessage::R);
  232. const bencode::BDE& id = getString(rDict, DHTMessage::ID);
  233. validateID(id);
  234. SharedHandle<DHTNode> remoteNode = getRemoteNode(id.uc(), ipaddr, port);
  235. if(messageType == DHTPingReplyMessage::PING) {
  236. return createPingReplyMessage(remoteNode, id.uc(), transactionID.s());
  237. } else if(messageType == DHTFindNodeReplyMessage::FIND_NODE) {
  238. return createFindNodeReplyMessage(remoteNode, dict, transactionID.s());
  239. } else if(messageType == DHTGetPeersReplyMessage::GET_PEERS) {
  240. const bencode::BDE& valuesList = rDict[DHTGetPeersReplyMessage::VALUES];
  241. if(valuesList.isList()) {
  242. return createGetPeersReplyMessageWithValues(remoteNode, dict,
  243. transactionID.s());
  244. } else {
  245. const bencode::BDE& nodes = rDict[DHTGetPeersReplyMessage::NODES];
  246. if(nodes.isString()) {
  247. return createGetPeersReplyMessageWithNodes(remoteNode, dict,
  248. transactionID.s());
  249. } else {
  250. throw DlAbortEx("Malformed DHT message: missing nodes/values");
  251. }
  252. }
  253. } else if(messageType == DHTAnnouncePeerReplyMessage::ANNOUNCE_PEER) {
  254. return createAnnouncePeerReplyMessage(remoteNode, transactionID.s());
  255. } else {
  256. throw DlAbortEx
  257. (StringFormat("Unsupported message type: %s", messageType.c_str()).str());
  258. }
  259. }
  260. void DHTMessageFactoryImpl::setCommonProperty(const SharedHandle<DHTAbstractMessage>& m)
  261. {
  262. m->setConnection(_connection);
  263. m->setMessageDispatcher(_dispatcher);
  264. m->setRoutingTable(_routingTable);
  265. WeakHandle<DHTMessageFactory> factory(this);
  266. m->setMessageFactory(factory);
  267. }
  268. SharedHandle<DHTMessage> DHTMessageFactoryImpl::createPingMessage(const SharedHandle<DHTNode>& remoteNode, const std::string& transactionID)
  269. {
  270. SharedHandle<DHTPingMessage> m(new DHTPingMessage(_localNode, remoteNode, transactionID));
  271. setCommonProperty(m);
  272. return m;
  273. }
  274. SharedHandle<DHTMessage>
  275. DHTMessageFactoryImpl::createPingReplyMessage(const SharedHandle<DHTNode>& remoteNode,
  276. const unsigned char* id,
  277. const std::string& transactionID)
  278. {
  279. SharedHandle<DHTPingReplyMessage> m(new DHTPingReplyMessage(_localNode, remoteNode, id, transactionID));
  280. setCommonProperty(m);
  281. return m;
  282. }
  283. SharedHandle<DHTMessage>
  284. DHTMessageFactoryImpl::createFindNodeMessage(const SharedHandle<DHTNode>& remoteNode,
  285. const unsigned char* targetNodeID,
  286. const std::string& transactionID)
  287. {
  288. SharedHandle<DHTFindNodeMessage> m(new DHTFindNodeMessage(_localNode, remoteNode, targetNodeID, transactionID));
  289. setCommonProperty(m);
  290. return m;
  291. }
  292. SharedHandle<DHTMessage>
  293. DHTMessageFactoryImpl::createFindNodeReplyMessage(const SharedHandle<DHTNode>& remoteNode,
  294. const std::deque<SharedHandle<DHTNode> >& closestKNodes,
  295. const std::string& transactionID)
  296. {
  297. SharedHandle<DHTFindNodeReplyMessage> m(new DHTFindNodeReplyMessage(_localNode, remoteNode, transactionID));
  298. m->setClosestKNodes(closestKNodes);
  299. setCommonProperty(m);
  300. return m;
  301. }
  302. std::deque<SharedHandle<DHTNode> >
  303. DHTMessageFactoryImpl::extractNodes(const unsigned char* src, size_t length)
  304. {
  305. if(length%26 != 0) {
  306. throw DlAbortEx("Nodes length is not multiple of 26");
  307. }
  308. std::deque<SharedHandle<DHTNode> > nodes;
  309. for(size_t offset = 0; offset < length; offset += 26) {
  310. SharedHandle<DHTNode> node(new DHTNode(src+offset));
  311. std::pair<std::string, uint16_t> addr =
  312. PeerMessageUtil::unpackcompact(src+offset+DHT_ID_LENGTH);
  313. if(addr.first.empty()) {
  314. continue;
  315. }
  316. node->setIPAddress(addr.first);
  317. node->setPort(addr.second);
  318. nodes.push_back(node);
  319. }
  320. return nodes;
  321. }
  322. SharedHandle<DHTMessage>
  323. DHTMessageFactoryImpl::createFindNodeReplyMessage
  324. (const SharedHandle<DHTNode>& remoteNode,
  325. const bencode::BDE& dict,
  326. const std::string& transactionID)
  327. {
  328. const bencode::BDE& nodesData =
  329. getString(getDictionary(dict, DHTResponseMessage::R),
  330. DHTFindNodeReplyMessage::NODES);
  331. std::deque<SharedHandle<DHTNode> > nodes = extractNodes(nodesData.uc(),
  332. nodesData.s().size());
  333. return createFindNodeReplyMessage(remoteNode, nodes, transactionID);
  334. }
  335. SharedHandle<DHTMessage>
  336. DHTMessageFactoryImpl::createGetPeersMessage(const SharedHandle<DHTNode>& remoteNode,
  337. const unsigned char* infoHash,
  338. const std::string& transactionID)
  339. {
  340. SharedHandle<DHTGetPeersMessage> m(new DHTGetPeersMessage(_localNode,
  341. remoteNode,
  342. infoHash,
  343. transactionID));
  344. m->setPeerAnnounceStorage(_peerAnnounceStorage);
  345. m->setTokenTracker(_tokenTracker);
  346. setCommonProperty(m);
  347. return m;
  348. }
  349. SharedHandle<DHTMessage>
  350. DHTMessageFactoryImpl::createGetPeersReplyMessageWithNodes
  351. (const SharedHandle<DHTNode>& remoteNode,
  352. const bencode::BDE& dict,
  353. const std::string& transactionID)
  354. {
  355. const bencode::BDE& rDict = getDictionary(dict, DHTResponseMessage::R);
  356. const bencode::BDE& nodesData = getString(rDict,
  357. DHTGetPeersReplyMessage::NODES);
  358. std::deque<SharedHandle<DHTNode> > nodes = extractNodes(nodesData.uc(),
  359. nodesData.s().size());
  360. const bencode::BDE& token = getString(rDict, DHTGetPeersReplyMessage::TOKEN);
  361. return createGetPeersReplyMessage(remoteNode, nodes, token.s(),
  362. transactionID);
  363. }
  364. SharedHandle<DHTMessage>
  365. DHTMessageFactoryImpl::createGetPeersReplyMessage(const SharedHandle<DHTNode>& remoteNode,
  366. const std::deque<SharedHandle<DHTNode> >& closestKNodes,
  367. const std::string& token,
  368. const std::string& transactionID)
  369. {
  370. SharedHandle<DHTGetPeersReplyMessage> m
  371. (new DHTGetPeersReplyMessage(_localNode, remoteNode, token, transactionID));
  372. m->setClosestKNodes(closestKNodes);
  373. setCommonProperty(m);
  374. return m;
  375. }
  376. SharedHandle<DHTMessage>
  377. DHTMessageFactoryImpl::createGetPeersReplyMessageWithValues
  378. (const SharedHandle<DHTNode>& remoteNode,
  379. const bencode::BDE& dict,
  380. const std::string& transactionID)
  381. {
  382. const bencode::BDE& rDict = getDictionary(dict, DHTResponseMessage::R);
  383. const bencode::BDE& valuesList = getList(rDict,
  384. DHTGetPeersReplyMessage::VALUES);
  385. std::deque<SharedHandle<Peer> > peers;
  386. for(bencode::BDE::List::const_iterator i = valuesList.listBegin();
  387. i != valuesList.listEnd(); ++i) {
  388. const bencode::BDE& data = *i;
  389. if(data.isString() && data.s().size() == 6) {
  390. std::pair<std::string, uint16_t> addr =
  391. PeerMessageUtil::unpackcompact(data.uc());
  392. PeerHandle peer(new Peer(addr.first, addr.second));
  393. peers.push_back(peer);
  394. }
  395. }
  396. const bencode::BDE& token = getString(rDict, DHTGetPeersReplyMessage::TOKEN);
  397. return createGetPeersReplyMessage(remoteNode, peers, token.s(),
  398. transactionID);
  399. }
  400. SharedHandle<DHTMessage>
  401. DHTMessageFactoryImpl::createGetPeersReplyMessage(const SharedHandle<DHTNode>& remoteNode,
  402. const std::deque<SharedHandle<Peer> >& values,
  403. const std::string& token,
  404. const std::string& transactionID)
  405. {
  406. SharedHandle<DHTGetPeersReplyMessage> m(new DHTGetPeersReplyMessage(_localNode, remoteNode, token, transactionID));
  407. m->setValues(values);
  408. setCommonProperty(m);
  409. return m;
  410. }
  411. SharedHandle<DHTMessage>
  412. DHTMessageFactoryImpl::createAnnouncePeerMessage(const SharedHandle<DHTNode>& remoteNode,
  413. const unsigned char* infoHash,
  414. uint16_t tcpPort,
  415. const std::string& token,
  416. const std::string& transactionID)
  417. {
  418. SharedHandle<DHTAnnouncePeerMessage> m
  419. (new DHTAnnouncePeerMessage(_localNode, remoteNode, infoHash, tcpPort, token, transactionID));
  420. m->setPeerAnnounceStorage(_peerAnnounceStorage);
  421. m->setTokenTracker(_tokenTracker);
  422. setCommonProperty(m);
  423. return m;
  424. }
  425. SharedHandle<DHTMessage>
  426. DHTMessageFactoryImpl::createAnnouncePeerReplyMessage(const SharedHandle<DHTNode>& remoteNode,
  427. const std::string& transactionID)
  428. {
  429. SharedHandle<DHTAnnouncePeerReplyMessage> m
  430. (new DHTAnnouncePeerReplyMessage(_localNode, remoteNode, transactionID));
  431. setCommonProperty(m);
  432. return m;
  433. }
  434. SharedHandle<DHTMessage>
  435. DHTMessageFactoryImpl::createUnknownMessage(const unsigned char* data, size_t length,
  436. const std::string& ipaddr, uint16_t port)
  437. {
  438. SharedHandle<DHTUnknownMessage> m
  439. (new DHTUnknownMessage(_localNode, data, length, ipaddr, port));
  440. return m;
  441. }
  442. void DHTMessageFactoryImpl::setRoutingTable(const WeakHandle<DHTRoutingTable>& routingTable)
  443. {
  444. _routingTable = routingTable;
  445. }
  446. void DHTMessageFactoryImpl::setConnection(const WeakHandle<DHTConnection>& connection)
  447. {
  448. _connection = connection;
  449. }
  450. void DHTMessageFactoryImpl::setMessageDispatcher(const WeakHandle<DHTMessageDispatcher>& dispatcher)
  451. {
  452. _dispatcher = dispatcher;
  453. }
  454. void DHTMessageFactoryImpl::setPeerAnnounceStorage(const WeakHandle<DHTPeerAnnounceStorage>& storage)
  455. {
  456. _peerAnnounceStorage = storage;
  457. }
  458. void DHTMessageFactoryImpl::setTokenTracker(const WeakHandle<DHTTokenTracker>& tokenTracker)
  459. {
  460. _tokenTracker = tokenTracker;
  461. }
  462. void DHTMessageFactoryImpl::setLocalNode(const SharedHandle<DHTNode>& localNode)
  463. {
  464. _localNode = localNode;
  465. }
  466. } // namespace aria2