PageRenderTime 27ms CodeModel.GetById 13ms RepoModel.GetById 0ms app.codeStats 0ms

/src/DHTSetup.cc

https://gitlab.com/yaksa/aria2
C++ | 309 lines | 249 code | 16 blank | 44 comment | 29 complexity | cc469565c961d5b8e512f0f810120da6 MD5 | raw file
  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() {}
  76. DHTSetup::~DHTSetup() {}
  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. PrefPtr prefEntryPointHost = family == AF_INET ? PREF_DHT_ENTRY_POINT_HOST
  170. : PREF_DHT_ENTRY_POINT_HOST6;
  171. if (!e->getOption()->get(prefEntryPointHost).empty()) {
  172. {
  173. PrefPtr prefEntryPointPort = family == AF_INET
  174. ? PREF_DHT_ENTRY_POINT_PORT
  175. : PREF_DHT_ENTRY_POINT_PORT6;
  176. std::pair<std::string, uint16_t> addr(
  177. e->getOption()->get(prefEntryPointHost),
  178. e->getOption()->getAsInt(prefEntryPointPort));
  179. std::vector<std::pair<std::string, uint16_t>> entryPoints;
  180. entryPoints.push_back(addr);
  181. auto command = make_unique<DHTEntryPointNameResolveCommand>(
  182. e->newCUID(), e, entryPoints);
  183. command->setBootstrapEnabled(true);
  184. command->setTaskQueue(taskQueue.get());
  185. command->setTaskFactory(taskFactory.get());
  186. command->setRoutingTable(routingTable.get());
  187. command->setLocalNode(localNode);
  188. tempCommands.push_back(std::move(command));
  189. }
  190. }
  191. else {
  192. A2_LOG_INFO("No DHT entry point specified.");
  193. }
  194. {
  195. auto command = make_unique<DHTInteractionCommand>(e->newCUID(), e);
  196. command->setMessageDispatcher(dispatcher.get());
  197. command->setMessageReceiver(receiver.get());
  198. command->setTaskQueue(taskQueue.get());
  199. command->setReadCheckSocket(connection->getSocket());
  200. command->setConnection(std::move(connection));
  201. command->setUDPTrackerClient(udpTrackerClient);
  202. tempRoutineCommands.push_back(std::move(command));
  203. }
  204. {
  205. auto command = make_unique<DHTTokenUpdateCommand>(
  206. e->newCUID(), e, DHT_TOKEN_UPDATE_INTERVAL);
  207. command->setTokenTracker(tokenTracker.get());
  208. tempCommands.push_back(std::move(command));
  209. }
  210. {
  211. auto command = make_unique<DHTBucketRefreshCommand>(
  212. e->newCUID(), e, DHT_BUCKET_REFRESH_CHECK_INTERVAL);
  213. command->setTaskQueue(taskQueue.get());
  214. command->setRoutingTable(routingTable.get());
  215. command->setTaskFactory(taskFactory.get());
  216. tempCommands.push_back(std::move(command));
  217. }
  218. {
  219. auto command = make_unique<DHTPeerAnnounceCommand>(
  220. e->newCUID(), e, DHT_PEER_ANNOUNCE_CHECK_INTERVAL);
  221. command->setPeerAnnounceStorage(peerAnnounceStorage.get());
  222. tempCommands.push_back(std::move(command));
  223. }
  224. {
  225. auto command =
  226. make_unique<DHTAutoSaveCommand>(e->newCUID(), e, family, 30_min);
  227. command->setLocalNode(localNode);
  228. command->setRoutingTable(routingTable.get());
  229. tempCommands.push_back(std::move(command));
  230. }
  231. // add deserialized nodes to routing table
  232. auto& desnodes = deserializer.getNodes();
  233. for (auto& node : desnodes) {
  234. routingTable->addNode(node);
  235. }
  236. if (!desnodes.empty()) {
  237. auto task = std::static_pointer_cast<DHTBucketRefreshTask>(
  238. taskFactory->createBucketRefreshTask());
  239. task->setForceRefresh(true);
  240. taskQueue->addPeriodicTask1(task);
  241. }
  242. // assign them into DHTRegistry
  243. if (family == AF_INET) {
  244. DHTRegistry::getMutableData().localNode = localNode;
  245. DHTRegistry::getMutableData().routingTable = std::move(routingTable);
  246. DHTRegistry::getMutableData().taskQueue = std::move(taskQueue);
  247. DHTRegistry::getMutableData().taskFactory = std::move(taskFactory);
  248. DHTRegistry::getMutableData().peerAnnounceStorage =
  249. std::move(peerAnnounceStorage);
  250. DHTRegistry::getMutableData().tokenTracker = std::move(tokenTracker);
  251. DHTRegistry::getMutableData().messageDispatcher = std::move(dispatcher);
  252. DHTRegistry::getMutableData().messageReceiver = std::move(receiver);
  253. DHTRegistry::getMutableData().messageFactory = std::move(factory);
  254. e->getBtRegistry()->setUDPTrackerClient(udpTrackerClient);
  255. DHTRegistry::setInitialized(true);
  256. }
  257. else {
  258. DHTRegistry::getMutableData6().localNode = localNode;
  259. DHTRegistry::getMutableData6().routingTable = std::move(routingTable);
  260. DHTRegistry::getMutableData6().taskQueue = std::move(taskQueue);
  261. DHTRegistry::getMutableData6().taskFactory = std::move(taskFactory);
  262. DHTRegistry::getMutableData6().peerAnnounceStorage =
  263. std::move(peerAnnounceStorage);
  264. DHTRegistry::getMutableData6().tokenTracker = std::move(tokenTracker);
  265. DHTRegistry::getMutableData6().messageDispatcher = std::move(dispatcher);
  266. DHTRegistry::getMutableData6().messageReceiver = std::move(receiver);
  267. DHTRegistry::getMutableData6().messageFactory = std::move(factory);
  268. DHTRegistry::setInitialized6(true);
  269. }
  270. if (e->getBtRegistry()->getUdpPort() == 0) {
  271. // We assign port last so that no exception gets in the way
  272. e->getBtRegistry()->setUdpPort(port);
  273. }
  274. }
  275. catch (RecoverableException& ex) {
  276. A2_LOG_ERROR_EX(fmt("Exception caught while initializing DHT functionality."
  277. " DHT is disabled."),
  278. ex);
  279. tempCommands.clear();
  280. tempRoutineCommands.clear();
  281. if (family == AF_INET) {
  282. DHTRegistry::clearData();
  283. e->getBtRegistry()->setUDPTrackerClient(
  284. std::shared_ptr<UDPTrackerClient>{});
  285. }
  286. else {
  287. DHTRegistry::clearData6();
  288. }
  289. }
  290. return std::make_pair(std::move(tempCommands),
  291. std::move(tempRoutineCommands));
  292. }
  293. } // namespace aria2