DHTSetup.cc 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  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 "DHTSetup.h"
  36. #include <algorithm>
  37. #include "LogFactory.h"
  38. #include "Logger.h"
  39. #include "util.h"
  40. #include "DHTNode.h"
  41. #include "DHTConnectionImpl.h"
  42. #include "DHTRoutingTable.h"
  43. #include "DHTMessageFactoryImpl.h"
  44. #include "DHTMessageTracker.h"
  45. #include "DHTMessageDispatcherImpl.h"
  46. #include "DHTMessageReceiver.h"
  47. #include "DHTTaskQueueImpl.h"
  48. #include "DHTTaskFactoryImpl.h"
  49. #include "DHTPeerAnnounceStorage.h"
  50. #include "DHTTokenTracker.h"
  51. #include "DHTInteractionCommand.h"
  52. #include "DHTTokenUpdateCommand.h"
  53. #include "DHTBucketRefreshCommand.h"
  54. #include "DHTPeerAnnounceCommand.h"
  55. #include "DHTEntryPointNameResolveCommand.h"
  56. #include "DHTAutoSaveCommand.h"
  57. #include "DHTTask.h"
  58. #include "DHTRoutingTableDeserializer.h"
  59. #include "DHTRegistry.h"
  60. #include "DHTBucketRefreshTask.h"
  61. #include "DHTMessageCallback.h"
  62. #include "DHTMessageTrackerEntry.h"
  63. #include "DHTMessageEntry.h"
  64. #include "UDPTrackerClient.h"
  65. #include "BtRegistry.h"
  66. #include "prefs.h"
  67. #include "Option.h"
  68. #include "SocketCore.h"
  69. #include "DlAbortEx.h"
  70. #include "RecoverableException.h"
  71. #include "a2functional.h"
  72. #include "DownloadEngine.h"
  73. #include "fmt.h"
  74. namespace aria2 {
  75. DHTSetup::DHTSetup() = default;
  76. DHTSetup::~DHTSetup() = default;
  77. std::pair<std::vector<std::unique_ptr<Command>>,
  78. std::vector<std::unique_ptr<Command>>>
  79. DHTSetup::setup(DownloadEngine* e, int family)
  80. {
  81. std::vector<std::unique_ptr<Command>> tempCommands;
  82. std::vector<std::unique_ptr<Command>> tempRoutineCommands;
  83. if ((family != AF_INET && family != AF_INET6) ||
  84. (family == AF_INET && DHTRegistry::isInitialized()) ||
  85. (family == AF_INET6 && DHTRegistry::isInitialized6())) {
  86. return {};
  87. }
  88. try {
  89. // load routing table and localnode id here
  90. std::shared_ptr<DHTNode> localNode;
  91. DHTRoutingTableDeserializer deserializer(family);
  92. const std::string& dhtFile = e->getOption()->get(
  93. family == AF_INET ? PREF_DHT_FILE_PATH : PREF_DHT_FILE_PATH6);
  94. try {
  95. deserializer.deserialize(dhtFile);
  96. localNode = deserializer.getLocalNode();
  97. }
  98. catch (RecoverableException& e) {
  99. A2_LOG_ERROR_EX(
  100. fmt("Exception caught while loading DHT routing table from %s",
  101. dhtFile.c_str()),
  102. e);
  103. }
  104. if (!localNode) {
  105. localNode = std::make_shared<DHTNode>();
  106. }
  107. uint16_t port;
  108. auto connection = make_unique<DHTConnectionImpl>(family);
  109. {
  110. port = e->getBtRegistry()->getUdpPort();
  111. const std::string& addr = e->getOption()->get(
  112. family == AF_INET ? PREF_DHT_LISTEN_ADDR : PREF_DHT_LISTEN_ADDR6);
  113. // If UDP port is already used, use the same port
  114. // number. Normally IPv4 port is available, then IPv6 port is
  115. // (especially for port >= 1024). We don't loose much by doing
  116. // this. We did the same thing in TCP socket. See BtSetup.cc.
  117. bool rv;
  118. if (port == 0) {
  119. auto sgl =
  120. util::parseIntSegments(e->getOption()->get(PREF_DHT_LISTEN_PORT));
  121. sgl.normalize();
  122. rv = connection->bind(port, addr, sgl);
  123. }
  124. else {
  125. rv = connection->bind(port, addr);
  126. }
  127. if (!rv) {
  128. throw DL_ABORT_EX("Error occurred while binding UDP port for DHT");
  129. }
  130. localNode->setPort(port);
  131. }
  132. A2_LOG_DEBUG(fmt("Initialized local node ID=%s",
  133. util::toHex(localNode->getID(), DHT_ID_LENGTH).c_str()));
  134. auto tracker = std::make_shared<DHTMessageTracker>();
  135. auto routingTable = make_unique<DHTRoutingTable>(localNode);
  136. auto factory = make_unique<DHTMessageFactoryImpl>(family);
  137. auto dispatcher = make_unique<DHTMessageDispatcherImpl>(tracker);
  138. auto receiver = make_unique<DHTMessageReceiver>(tracker);
  139. auto taskQueue = make_unique<DHTTaskQueueImpl>();
  140. auto taskFactory = make_unique<DHTTaskFactoryImpl>();
  141. auto peerAnnounceStorage = make_unique<DHTPeerAnnounceStorage>();
  142. auto tokenTracker = make_unique<DHTTokenTracker>();
  143. // For now, UDPTrackerClient was enabled along with DHT
  144. auto udpTrackerClient = std::make_shared<UDPTrackerClient>();
  145. const auto messageTimeout =
  146. e->getOption()->getAsInt(PREF_DHT_MESSAGE_TIMEOUT);
  147. // wiring up
  148. tracker->setRoutingTable(routingTable.get());
  149. tracker->setMessageFactory(factory.get());
  150. dispatcher->setTimeout(std::chrono::seconds(messageTimeout));
  151. receiver->setMessageFactory(factory.get());
  152. receiver->setRoutingTable(routingTable.get());
  153. taskFactory->setLocalNode(localNode);
  154. taskFactory->setRoutingTable(routingTable.get());
  155. taskFactory->setMessageDispatcher(dispatcher.get());
  156. taskFactory->setMessageFactory(factory.get());
  157. taskFactory->setTaskQueue(taskQueue.get());
  158. taskFactory->setTimeout(std::chrono::seconds(messageTimeout));
  159. routingTable->setTaskQueue(taskQueue.get());
  160. routingTable->setTaskFactory(taskFactory.get());
  161. peerAnnounceStorage->setTaskQueue(taskQueue.get());
  162. peerAnnounceStorage->setTaskFactory(taskFactory.get());
  163. factory->setRoutingTable(routingTable.get());
  164. factory->setConnection(connection.get());
  165. factory->setMessageDispatcher(dispatcher.get());
  166. factory->setPeerAnnounceStorage(peerAnnounceStorage.get());
  167. factory->setTokenTracker(tokenTracker.get());
  168. factory->setLocalNode(localNode);
  169. factory->setBtRegistry(e->getBtRegistry().get());
  170. PrefPtr prefEntryPointHost = family == AF_INET ? PREF_DHT_ENTRY_POINT_HOST
  171. : PREF_DHT_ENTRY_POINT_HOST6;
  172. if (!e->getOption()->get(prefEntryPointHost).empty()) {
  173. {
  174. PrefPtr prefEntryPointPort = family == AF_INET
  175. ? PREF_DHT_ENTRY_POINT_PORT
  176. : PREF_DHT_ENTRY_POINT_PORT6;
  177. std::pair<std::string, uint16_t> addr(
  178. e->getOption()->get(prefEntryPointHost),
  179. e->getOption()->getAsInt(prefEntryPointPort));
  180. std::vector<std::pair<std::string, uint16_t>> entryPoints;
  181. entryPoints.push_back(addr);
  182. auto command = make_unique<DHTEntryPointNameResolveCommand>(
  183. e->newCUID(), e, family, entryPoints);
  184. command->setBootstrapEnabled(true);
  185. command->setTaskQueue(taskQueue.get());
  186. command->setTaskFactory(taskFactory.get());
  187. command->setRoutingTable(routingTable.get());
  188. command->setLocalNode(localNode);
  189. tempCommands.push_back(std::move(command));
  190. }
  191. }
  192. else {
  193. A2_LOG_INFO("No DHT entry point specified.");
  194. }
  195. {
  196. auto command = make_unique<DHTInteractionCommand>(e->newCUID(), e);
  197. command->setMessageDispatcher(dispatcher.get());
  198. command->setMessageReceiver(receiver.get());
  199. command->setTaskQueue(taskQueue.get());
  200. command->setReadCheckSocket(connection->getSocket());
  201. command->setConnection(std::move(connection));
  202. command->setUDPTrackerClient(udpTrackerClient);
  203. tempRoutineCommands.push_back(std::move(command));
  204. }
  205. {
  206. auto command = make_unique<DHTTokenUpdateCommand>(
  207. e->newCUID(), e, DHT_TOKEN_UPDATE_INTERVAL);
  208. command->setTokenTracker(tokenTracker.get());
  209. tempCommands.push_back(std::move(command));
  210. }
  211. {
  212. auto command = make_unique<DHTBucketRefreshCommand>(
  213. e->newCUID(), e, DHT_BUCKET_REFRESH_CHECK_INTERVAL);
  214. command->setTaskQueue(taskQueue.get());
  215. command->setRoutingTable(routingTable.get());
  216. command->setTaskFactory(taskFactory.get());
  217. tempCommands.push_back(std::move(command));
  218. }
  219. {
  220. auto command = make_unique<DHTPeerAnnounceCommand>(
  221. e->newCUID(), e, DHT_PEER_ANNOUNCE_CHECK_INTERVAL);
  222. command->setPeerAnnounceStorage(peerAnnounceStorage.get());
  223. tempCommands.push_back(std::move(command));
  224. }
  225. {
  226. auto command =
  227. make_unique<DHTAutoSaveCommand>(e->newCUID(), e, family, 30_min);
  228. command->setLocalNode(localNode);
  229. command->setRoutingTable(routingTable.get());
  230. tempCommands.push_back(std::move(command));
  231. }
  232. // add deserialized nodes to routing table
  233. auto& desnodes = deserializer.getNodes();
  234. for (auto& node : desnodes) {
  235. routingTable->addNode(node);
  236. }
  237. if (!desnodes.empty()) {
  238. auto task = std::static_pointer_cast<DHTBucketRefreshTask>(
  239. taskFactory->createBucketRefreshTask());
  240. task->setForceRefresh(true);
  241. taskQueue->addPeriodicTask1(task);
  242. }
  243. // assign them into DHTRegistry
  244. if (family == AF_INET) {
  245. DHTRegistry::getMutableData().localNode = localNode;
  246. DHTRegistry::getMutableData().routingTable = std::move(routingTable);
  247. DHTRegistry::getMutableData().taskQueue = std::move(taskQueue);
  248. DHTRegistry::getMutableData().taskFactory = std::move(taskFactory);
  249. DHTRegistry::getMutableData().peerAnnounceStorage =
  250. std::move(peerAnnounceStorage);
  251. DHTRegistry::getMutableData().tokenTracker = std::move(tokenTracker);
  252. DHTRegistry::getMutableData().messageDispatcher = std::move(dispatcher);
  253. DHTRegistry::getMutableData().messageReceiver = std::move(receiver);
  254. DHTRegistry::getMutableData().messageFactory = std::move(factory);
  255. e->getBtRegistry()->setUDPTrackerClient(udpTrackerClient);
  256. DHTRegistry::setInitialized(true);
  257. }
  258. else {
  259. DHTRegistry::getMutableData6().localNode = localNode;
  260. DHTRegistry::getMutableData6().routingTable = std::move(routingTable);
  261. DHTRegistry::getMutableData6().taskQueue = std::move(taskQueue);
  262. DHTRegistry::getMutableData6().taskFactory = std::move(taskFactory);
  263. DHTRegistry::getMutableData6().peerAnnounceStorage =
  264. std::move(peerAnnounceStorage);
  265. DHTRegistry::getMutableData6().tokenTracker = std::move(tokenTracker);
  266. DHTRegistry::getMutableData6().messageDispatcher = std::move(dispatcher);
  267. DHTRegistry::getMutableData6().messageReceiver = std::move(receiver);
  268. DHTRegistry::getMutableData6().messageFactory = std::move(factory);
  269. DHTRegistry::setInitialized6(true);
  270. }
  271. if (e->getBtRegistry()->getUdpPort() == 0) {
  272. // We assign port last so that no exception gets in the way
  273. e->getBtRegistry()->setUdpPort(port);
  274. }
  275. }
  276. catch (RecoverableException& ex) {
  277. A2_LOG_ERROR_EX(fmt("Exception caught while initializing DHT functionality."
  278. " DHT is disabled."),
  279. ex);
  280. tempCommands.clear();
  281. tempRoutineCommands.clear();
  282. if (family == AF_INET) {
  283. DHTRegistry::clearData();
  284. e->getBtRegistry()->setUDPTrackerClient(
  285. std::shared_ptr<UDPTrackerClient>{});
  286. }
  287. else {
  288. DHTRegistry::clearData6();
  289. }
  290. }
  291. return std::make_pair(std::move(tempCommands),
  292. std::move(tempRoutineCommands));
  293. }
  294. } // namespace aria2