DHTMessageFactoryImpl.cc 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473
  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 "LogFactory.h"
  37. #include "DlAbortEx.h"
  38. #include "Data.h"
  39. #include "Dictionary.h"
  40. #include "List.h"
  41. #include "DHTNode.h"
  42. #include "DHTRoutingTable.h"
  43. #include "DHTPingMessage.h"
  44. #include "DHTPingReplyMessage.h"
  45. #include "DHTFindNodeMessage.h"
  46. #include "DHTFindNodeReplyMessage.h"
  47. #include "DHTGetPeersMessage.h"
  48. #include "DHTGetPeersReplyMessage.h"
  49. #include "DHTAnnouncePeerMessage.h"
  50. #include "DHTAnnouncePeerReplyMessage.h"
  51. #include "DHTUnknownMessage.h"
  52. #include "DHTConnection.h"
  53. #include "DHTMessageDispatcher.h"
  54. #include "DHTPeerAnnounceStorage.h"
  55. #include "DHTTokenTracker.h"
  56. #include "DHTMessageCallback.h"
  57. #include "PeerMessageUtil.h"
  58. #include "BtRuntime.h"
  59. #include "Util.h"
  60. #include "Peer.h"
  61. #include "Logger.h"
  62. #include "StringFormat.h"
  63. #include <cstring>
  64. #include <utility>
  65. namespace aria2 {
  66. DHTMessageFactoryImpl::DHTMessageFactoryImpl():
  67. _logger(LogFactory::getInstance()) {}
  68. DHTMessageFactoryImpl::~DHTMessageFactoryImpl() {}
  69. SharedHandle<DHTNode>
  70. DHTMessageFactoryImpl::getRemoteNode(const unsigned char* id, const std::string& ipaddr, uint16_t port) const
  71. {
  72. SharedHandle<DHTNode> node = _routingTable->getNode(id, ipaddr, port);
  73. if(node.isNull()) {
  74. node.reset(new DHTNode(id));
  75. node->setIPAddress(ipaddr);
  76. node->setPort(port);
  77. }
  78. return node;
  79. }
  80. static const Dictionary* getDictionary(const Dictionary* d, const std::string& key)
  81. {
  82. const Dictionary* c = dynamic_cast<const Dictionary*>(d->get(key));
  83. if(c) {
  84. return c;
  85. } else {
  86. throw DlAbortEx
  87. (StringFormat("Malformed DHT message. Missing %s", key.c_str()).str());
  88. }
  89. }
  90. static const Data* getData(const Dictionary* d, const std::string& key)
  91. {
  92. const Data* c = dynamic_cast<const Data*>(d->get(key));
  93. if(c) {
  94. return c;
  95. } else {
  96. throw DlAbortEx
  97. (StringFormat("Malformed DHT message. Missing %s", key.c_str()).str());
  98. }
  99. }
  100. static const Data* getData(const List* l, size_t index)
  101. {
  102. const Data* c = dynamic_cast<const Data*>(l->getList()[index]);
  103. if(c) {
  104. return c;
  105. } else {
  106. throw DlAbortEx
  107. (StringFormat("Malformed DHT message. element[%u] is not Data.",
  108. index).str());
  109. }
  110. }
  111. static const List* getList(const Dictionary* d, const std::string& key)
  112. {
  113. const List* l = dynamic_cast<const List*>(d->get(key));
  114. if(l) {
  115. return l;
  116. } else {
  117. throw DlAbortEx
  118. (StringFormat("Malformed DHT message. Missing %s", key.c_str()).str());
  119. }
  120. }
  121. void DHTMessageFactoryImpl::validateID(const Data* id) const
  122. {
  123. if(id->getLen() != DHT_ID_LENGTH) {
  124. throw DlAbortEx
  125. (StringFormat("Malformed DHT message. Invalid ID length. Expected:%d, Actual:%d", DHT_ID_LENGTH, id->getLen()).str());
  126. }
  127. }
  128. void DHTMessageFactoryImpl::validateIDMatch(const unsigned char* expected, const unsigned char* actual) const
  129. {
  130. if(memcmp(expected, actual, DHT_ID_LENGTH) != 0) {
  131. //throw DlAbortEx("Different ID received.");
  132. }
  133. }
  134. void DHTMessageFactoryImpl::validatePort(const Data* i) const
  135. {
  136. if(!i->isNumber()) {
  137. throw DlAbortEx
  138. (StringFormat("Malformed DHT message. Invalid port=%s",
  139. Util::toHex(i->toString()).c_str()).str());
  140. }
  141. uint32_t port = i->toInt();
  142. if(UINT16_MAX < port) {
  143. throw DlAbortEx
  144. (StringFormat("Malformed DHT message. Invalid port=%u", port).str());
  145. }
  146. }
  147. SharedHandle<DHTMessage> DHTMessageFactoryImpl::createQueryMessage(const Dictionary* d,
  148. const std::string& ipaddr,
  149. uint16_t port)
  150. {
  151. const Data* q = getData(d, DHTQueryMessage::Q);
  152. const Data* t = getData(d, DHTMessage::T);
  153. const Data* y = getData(d, DHTMessage::Y);
  154. const Dictionary* a = getDictionary(d, DHTQueryMessage::A);
  155. if(y->toString() != DHTQueryMessage::Q) {
  156. throw DlAbortEx("Malformed DHT message. y != q");
  157. }
  158. const Data* id = getData(getDictionary(d, DHTQueryMessage::A), DHTMessage::ID);
  159. validateID(id);
  160. SharedHandle<DHTNode> remoteNode = getRemoteNode(id->getData(), ipaddr, port);
  161. std::string messageType = q->toString();
  162. std::string transactionID = t->toString();
  163. if(messageType == DHTPingMessage::PING) {
  164. return createPingMessage(remoteNode, transactionID);
  165. } else if(messageType == DHTFindNodeMessage::FIND_NODE) {
  166. const Data* targetNodeID = getData(a, DHTFindNodeMessage::TARGET_NODE);
  167. validateID(targetNodeID);
  168. return createFindNodeMessage(remoteNode, targetNodeID->getData(),
  169. transactionID);
  170. } else if(messageType == DHTGetPeersMessage::GET_PEERS) {
  171. const Data* infoHash = getData(a, DHTGetPeersMessage::INFO_HASH);
  172. validateID(infoHash);
  173. return createGetPeersMessage(remoteNode,
  174. infoHash->getData(), transactionID);
  175. } else if(messageType == DHTAnnouncePeerMessage::ANNOUNCE_PEER) {
  176. const Data* infoHash = getData(a, DHTAnnouncePeerMessage::INFO_HASH);
  177. validateID(infoHash);
  178. const Data* port = getData(a, DHTAnnouncePeerMessage::PORT);
  179. validatePort(port);
  180. const Data* token = getData(a, DHTAnnouncePeerMessage::TOKEN);
  181. return createAnnouncePeerMessage(remoteNode, infoHash->getData(),
  182. static_cast<uint16_t>(port->toInt()),
  183. token->toString(), transactionID);
  184. } else {
  185. throw DlAbortEx
  186. (StringFormat("Unsupported message type: %s", messageType.c_str()).str());
  187. }
  188. }
  189. SharedHandle<DHTMessage>
  190. DHTMessageFactoryImpl::createResponseMessage(const std::string& messageType,
  191. const Dictionary* d,
  192. const SharedHandle<DHTNode>& remoteNode)
  193. {
  194. const Data* t = getData(d, DHTMessage::T);
  195. const Data* y = getData(d, DHTMessage::Y);
  196. if(y->toString() == DHTUnknownMessage::E) {
  197. // for now, just report error message arrived and throw exception.
  198. const List* e = getList(d, DHTUnknownMessage::E);
  199. if(e->getList().size() == 2) {
  200. _logger->info("Received Error DHT message. code=%s, msg=%s",
  201. Util::urlencode(getData(e, 0)->toString()).c_str(),
  202. Util::urlencode(getData(e, 1)->toString()).c_str());
  203. } else {
  204. _logger->debug("e doesn't have 2 elements.");
  205. }
  206. throw DlAbortEx("Received Error DHT message.");
  207. } else if(y->toString() != DHTResponseMessage::R) {
  208. throw DlAbortEx
  209. (StringFormat("Malformed DHT message. y != r: y=%s",
  210. Util::urlencode(y->toString()).c_str()).str());
  211. }
  212. const Dictionary* r = getDictionary(d, DHTResponseMessage::R);
  213. const Data* id = getData(r, DHTMessage::ID);
  214. validateID(id);
  215. validateIDMatch(remoteNode->getID(), id->getData());
  216. std::string transactionID = t->toString();
  217. if(messageType == DHTPingReplyMessage::PING) {
  218. return createPingReplyMessage(remoteNode,
  219. id->getData(), transactionID);
  220. } else if(messageType == DHTFindNodeReplyMessage::FIND_NODE) {
  221. return createFindNodeReplyMessage(remoteNode, d, transactionID);
  222. } else if(messageType == DHTGetPeersReplyMessage::GET_PEERS) {
  223. const List* values =
  224. dynamic_cast<const List*>(r->get(DHTGetPeersReplyMessage::VALUES));
  225. if(values) {
  226. return createGetPeersReplyMessageWithValues(remoteNode, d, transactionID);
  227. } else {
  228. const Data* nodes = dynamic_cast<const Data*>(r->get(DHTGetPeersReplyMessage::NODES));
  229. if(nodes) {
  230. return createGetPeersReplyMessageWithNodes(remoteNode, d, transactionID);
  231. } else {
  232. throw DlAbortEx("Malformed DHT message: missing nodes/values");
  233. }
  234. }
  235. } else if(messageType == DHTAnnouncePeerReplyMessage::ANNOUNCE_PEER) {
  236. return createAnnouncePeerReplyMessage(remoteNode, transactionID);
  237. } else {
  238. throw DlAbortEx
  239. (StringFormat("Unsupported message type: %s", messageType.c_str()).str());
  240. }
  241. }
  242. void DHTMessageFactoryImpl::setCommonProperty(const SharedHandle<DHTAbstractMessage>& m)
  243. {
  244. m->setConnection(_connection);
  245. m->setMessageDispatcher(_dispatcher);
  246. m->setRoutingTable(_routingTable);
  247. WeakHandle<DHTMessageFactory> factory(this);
  248. m->setMessageFactory(factory);
  249. }
  250. SharedHandle<DHTMessage> DHTMessageFactoryImpl::createPingMessage(const SharedHandle<DHTNode>& remoteNode, const std::string& transactionID)
  251. {
  252. SharedHandle<DHTPingMessage> m(new DHTPingMessage(_localNode, remoteNode, transactionID));
  253. setCommonProperty(m);
  254. return m;
  255. }
  256. SharedHandle<DHTMessage>
  257. DHTMessageFactoryImpl::createPingReplyMessage(const SharedHandle<DHTNode>& remoteNode,
  258. const unsigned char* id,
  259. const std::string& transactionID)
  260. {
  261. SharedHandle<DHTPingReplyMessage> m(new DHTPingReplyMessage(_localNode, remoteNode, id, transactionID));
  262. setCommonProperty(m);
  263. return m;
  264. }
  265. SharedHandle<DHTMessage>
  266. DHTMessageFactoryImpl::createFindNodeMessage(const SharedHandle<DHTNode>& remoteNode,
  267. const unsigned char* targetNodeID,
  268. const std::string& transactionID)
  269. {
  270. SharedHandle<DHTFindNodeMessage> m(new DHTFindNodeMessage(_localNode, remoteNode, targetNodeID, transactionID));
  271. setCommonProperty(m);
  272. return m;
  273. }
  274. SharedHandle<DHTMessage>
  275. DHTMessageFactoryImpl::createFindNodeReplyMessage(const SharedHandle<DHTNode>& remoteNode,
  276. const std::deque<SharedHandle<DHTNode> >& closestKNodes,
  277. const std::string& transactionID)
  278. {
  279. SharedHandle<DHTFindNodeReplyMessage> m(new DHTFindNodeReplyMessage(_localNode, remoteNode, transactionID));
  280. m->setClosestKNodes(closestKNodes);
  281. setCommonProperty(m);
  282. return m;
  283. }
  284. std::deque<SharedHandle<DHTNode> >
  285. DHTMessageFactoryImpl::extractNodes(const unsigned char* src, size_t length)
  286. {
  287. if(length%26 != 0) {
  288. throw DlAbortEx("Nodes length is not multiple of 26");
  289. }
  290. std::deque<SharedHandle<DHTNode> > nodes;
  291. for(size_t offset = 0; offset < length; offset += 26) {
  292. SharedHandle<DHTNode> node(new DHTNode(src+offset));
  293. std::pair<std::string, uint16_t> addr =
  294. PeerMessageUtil::unpackcompact(src+offset+DHT_ID_LENGTH);
  295. if(addr.first.empty()) {
  296. continue;
  297. }
  298. node->setIPAddress(addr.first);
  299. node->setPort(addr.second);
  300. nodes.push_back(node);
  301. }
  302. return nodes;
  303. }
  304. SharedHandle<DHTMessage>
  305. DHTMessageFactoryImpl::createFindNodeReplyMessage(const SharedHandle<DHTNode>& remoteNode,
  306. const Dictionary* d,
  307. const std::string& transactionID)
  308. {
  309. const Data* nodesData = getData(getDictionary(d, DHTResponseMessage::R), DHTFindNodeReplyMessage::NODES);
  310. std::deque<SharedHandle<DHTNode> > nodes = extractNodes(nodesData->getData(), nodesData->getLen());
  311. return createFindNodeReplyMessage(remoteNode, nodes, transactionID);
  312. }
  313. SharedHandle<DHTMessage>
  314. DHTMessageFactoryImpl::createGetPeersMessage(const SharedHandle<DHTNode>& remoteNode,
  315. const unsigned char* infoHash,
  316. const std::string& transactionID)
  317. {
  318. SharedHandle<DHTGetPeersMessage> m(new DHTGetPeersMessage(_localNode,
  319. remoteNode,
  320. infoHash,
  321. transactionID));
  322. m->setPeerAnnounceStorage(_peerAnnounceStorage);
  323. m->setTokenTracker(_tokenTracker);
  324. setCommonProperty(m);
  325. return m;
  326. }
  327. SharedHandle<DHTMessage>
  328. DHTMessageFactoryImpl::createGetPeersReplyMessageWithNodes(const SharedHandle<DHTNode>& remoteNode,
  329. const Dictionary* d,
  330. const std::string& transactionID)
  331. {
  332. const Dictionary* r = getDictionary(d, DHTResponseMessage::R);
  333. const Data* nodesData = getData(r, DHTGetPeersReplyMessage::NODES);
  334. std::deque<SharedHandle<DHTNode> > nodes = extractNodes(nodesData->getData(), nodesData->getLen());
  335. const Data* token = getData(r, DHTGetPeersReplyMessage::TOKEN);
  336. return createGetPeersReplyMessage(remoteNode, nodes, token->toString(),
  337. transactionID);
  338. }
  339. SharedHandle<DHTMessage>
  340. DHTMessageFactoryImpl::createGetPeersReplyMessage(const SharedHandle<DHTNode>& remoteNode,
  341. const std::deque<SharedHandle<DHTNode> >& closestKNodes,
  342. const std::string& token,
  343. const std::string& transactionID)
  344. {
  345. SharedHandle<DHTGetPeersReplyMessage> m
  346. (new DHTGetPeersReplyMessage(_localNode, remoteNode, token, transactionID));
  347. m->setClosestKNodes(closestKNodes);
  348. setCommonProperty(m);
  349. return m;
  350. }
  351. SharedHandle<DHTMessage>
  352. DHTMessageFactoryImpl::createGetPeersReplyMessageWithValues(const SharedHandle<DHTNode>& remoteNode,
  353. const Dictionary* d,
  354. const std::string& transactionID)
  355. {
  356. const Dictionary* r = getDictionary(d, DHTResponseMessage::R);
  357. const List* valuesList = getList(r, DHTGetPeersReplyMessage::VALUES);
  358. std::deque<SharedHandle<Peer> > peers;
  359. for(std::deque<MetaEntry*>::const_iterator i = valuesList->getList().begin(); i != valuesList->getList().end(); ++i) {
  360. const Data* data = dynamic_cast<const Data*>(*i);
  361. if(data && data->getLen() == 6) {
  362. std::pair<std::string, uint16_t> addr = PeerMessageUtil::unpackcompact(data->getData());
  363. PeerHandle peer(new Peer(addr.first, addr.second));
  364. peers.push_back(peer);
  365. }
  366. }
  367. const Data* token = getData(r, DHTGetPeersReplyMessage::TOKEN);
  368. return createGetPeersReplyMessage(remoteNode, peers, token->toString(),
  369. transactionID);
  370. }
  371. SharedHandle<DHTMessage>
  372. DHTMessageFactoryImpl::createGetPeersReplyMessage(const SharedHandle<DHTNode>& remoteNode,
  373. const std::deque<SharedHandle<Peer> >& values,
  374. const std::string& token,
  375. const std::string& transactionID)
  376. {
  377. SharedHandle<DHTGetPeersReplyMessage> m(new DHTGetPeersReplyMessage(_localNode, remoteNode, token, transactionID));
  378. m->setValues(values);
  379. setCommonProperty(m);
  380. return m;
  381. }
  382. SharedHandle<DHTMessage>
  383. DHTMessageFactoryImpl::createAnnouncePeerMessage(const SharedHandle<DHTNode>& remoteNode,
  384. const unsigned char* infoHash,
  385. uint16_t tcpPort,
  386. const std::string& token,
  387. const std::string& transactionID)
  388. {
  389. SharedHandle<DHTAnnouncePeerMessage> m
  390. (new DHTAnnouncePeerMessage(_localNode, remoteNode, infoHash, tcpPort, token, transactionID));
  391. m->setPeerAnnounceStorage(_peerAnnounceStorage);
  392. m->setTokenTracker(_tokenTracker);
  393. setCommonProperty(m);
  394. return m;
  395. }
  396. SharedHandle<DHTMessage>
  397. DHTMessageFactoryImpl::createAnnouncePeerReplyMessage(const SharedHandle<DHTNode>& remoteNode,
  398. const std::string& transactionID)
  399. {
  400. SharedHandle<DHTAnnouncePeerReplyMessage> m
  401. (new DHTAnnouncePeerReplyMessage(_localNode, remoteNode, transactionID));
  402. setCommonProperty(m);
  403. return m;
  404. }
  405. SharedHandle<DHTMessage>
  406. DHTMessageFactoryImpl::createUnknownMessage(const unsigned char* data, size_t length,
  407. const std::string& ipaddr, uint16_t port)
  408. {
  409. SharedHandle<DHTUnknownMessage> m
  410. (new DHTUnknownMessage(_localNode, data, length, ipaddr, port));
  411. return m;
  412. }
  413. void DHTMessageFactoryImpl::setRoutingTable(const WeakHandle<DHTRoutingTable>& routingTable)
  414. {
  415. _routingTable = routingTable;
  416. }
  417. void DHTMessageFactoryImpl::setConnection(const WeakHandle<DHTConnection>& connection)
  418. {
  419. _connection = connection;
  420. }
  421. void DHTMessageFactoryImpl::setMessageDispatcher(const WeakHandle<DHTMessageDispatcher>& dispatcher)
  422. {
  423. _dispatcher = dispatcher;
  424. }
  425. void DHTMessageFactoryImpl::setPeerAnnounceStorage(const WeakHandle<DHTPeerAnnounceStorage>& storage)
  426. {
  427. _peerAnnounceStorage = storage;
  428. }
  429. void DHTMessageFactoryImpl::setTokenTracker(const WeakHandle<DHTTokenTracker>& tokenTracker)
  430. {
  431. _tokenTracker = tokenTracker;
  432. }
  433. void DHTMessageFactoryImpl::setLocalNode(const SharedHandle<DHTNode>& localNode)
  434. {
  435. _localNode = localNode;
  436. }
  437. } // namespace aria2