DHTMessageFactoryImpl.cc 17 KB

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