DHTSetup.cc 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  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 <fstream>
  37. #include <algorithm>
  38. #include "LogFactory.h"
  39. #include "Logger.h"
  40. #include "util.h"
  41. #include "File.h"
  42. #include "DHTNode.h"
  43. #include "DHTConnectionImpl.h"
  44. #include "DHTRoutingTable.h"
  45. #include "DHTMessageFactoryImpl.h"
  46. #include "DHTMessageTracker.h"
  47. #include "DHTMessageDispatcherImpl.h"
  48. #include "DHTMessageReceiver.h"
  49. #include "DHTTaskQueueImpl.h"
  50. #include "DHTTaskFactoryImpl.h"
  51. #include "DHTPeerAnnounceStorage.h"
  52. #include "DHTTokenTracker.h"
  53. #include "DHTInteractionCommand.h"
  54. #include "DHTTokenUpdateCommand.h"
  55. #include "DHTBucketRefreshCommand.h"
  56. #include "DHTPeerAnnounceCommand.h"
  57. #include "DHTEntryPointNameResolveCommand.h"
  58. #include "DHTAutoSaveCommand.h"
  59. #include "DHTTask.h"
  60. #include "DHTRoutingTableDeserializer.h"
  61. #include "DHTRegistry.h"
  62. #include "DHTBucketRefreshTask.h"
  63. #include "DHTMessageCallback.h"
  64. #include "prefs.h"
  65. #include "Option.h"
  66. #include "SocketCore.h"
  67. #include "DlAbortEx.h"
  68. #include "RecoverableException.h"
  69. #include "a2functional.h"
  70. #include "DownloadEngine.h"
  71. #include "wallclock.h"
  72. #include "RequestGroupMan.h"
  73. #include "FileAllocationEntry.h"
  74. #include "CheckIntegrityEntry.h"
  75. #include "ServerStatMan.h"
  76. #include "FileEntry.h"
  77. namespace aria2 {
  78. // TODO DownloadEngine should hold this flag.
  79. bool DHTSetup::_initialized = false;
  80. DHTSetup::DHTSetup():_logger(LogFactory::getInstance()) {}
  81. DHTSetup::~DHTSetup() {}
  82. void DHTSetup::setup(std::vector<Command*>& commands, DownloadEngine* e)
  83. {
  84. if(_initialized) {
  85. return;
  86. }
  87. std::vector<Command*> tempCommands;
  88. try {
  89. // load routing table and localnode id here
  90. SharedHandle<DHTNode> localNode;
  91. DHTRoutingTableDeserializer deserializer;
  92. std::string dhtFile = e->getOption()->get(PREF_DHT_FILE_PATH);
  93. try {
  94. std::ifstream in(dhtFile.c_str(), std::ios::binary);
  95. if(!in) {
  96. throw DL_ABORT_EX("Could not open file");
  97. }
  98. deserializer.deserialize(in);
  99. localNode = deserializer.getLocalNode();
  100. } catch(RecoverableException& e) {
  101. _logger->error("Exception caught while loading DHT routing table from %s",
  102. e, dhtFile.c_str());
  103. }
  104. if(localNode.isNull()) {
  105. localNode.reset(new DHTNode());
  106. }
  107. SharedHandle<DHTConnectionImpl> connection(new DHTConnectionImpl());
  108. {
  109. IntSequence seq =
  110. util::parseIntRange(e->getOption()->get(PREF_DHT_LISTEN_PORT));
  111. uint16_t port;
  112. if(!connection->bind(port, seq)) {
  113. throw DL_ABORT_EX("Error occurred while binding port for DHT");
  114. }
  115. localNode->setPort(port);
  116. }
  117. if(_logger->debug()) {
  118. _logger->debug("Initialized local node ID=%s",
  119. util::toHex(localNode->getID(), DHT_ID_LENGTH).c_str());
  120. }
  121. SharedHandle<DHTRoutingTable> routingTable(new DHTRoutingTable(localNode));
  122. SharedHandle<DHTMessageFactoryImpl> factory(new DHTMessageFactoryImpl());
  123. SharedHandle<DHTMessageTracker> tracker(new DHTMessageTracker());
  124. SharedHandle<DHTMessageDispatcherImpl> dispatcher(new DHTMessageDispatcherImpl(tracker));
  125. SharedHandle<DHTMessageReceiver> receiver(new DHTMessageReceiver(tracker));
  126. SharedHandle<DHTTaskQueue> taskQueue(new DHTTaskQueueImpl());
  127. SharedHandle<DHTTaskFactoryImpl> taskFactory(new DHTTaskFactoryImpl());
  128. SharedHandle<DHTPeerAnnounceStorage> peerAnnounceStorage(new DHTPeerAnnounceStorage());
  129. SharedHandle<DHTTokenTracker> tokenTracker(new DHTTokenTracker());
  130. const time_t messageTimeout = e->getOption()->getAsInt(PREF_DHT_MESSAGE_TIMEOUT);
  131. // wiring up
  132. tracker->setRoutingTable(routingTable);
  133. tracker->setMessageFactory(factory);
  134. dispatcher->setTimeout(messageTimeout);
  135. receiver->setConnection(connection);
  136. receiver->setMessageFactory(factory);
  137. receiver->setRoutingTable(routingTable);
  138. taskFactory->setLocalNode(localNode);
  139. taskFactory->setRoutingTable(routingTable);
  140. taskFactory->setMessageDispatcher(dispatcher);
  141. taskFactory->setMessageFactory(factory);
  142. taskFactory->setTaskQueue(taskQueue);
  143. taskFactory->setTimeout(messageTimeout);
  144. routingTable->setTaskQueue(taskQueue);
  145. routingTable->setTaskFactory(taskFactory);
  146. peerAnnounceStorage->setTaskQueue(taskQueue);
  147. peerAnnounceStorage->setTaskFactory(taskFactory);
  148. factory->setRoutingTable(routingTable);
  149. factory->setConnection(connection);
  150. factory->setMessageDispatcher(dispatcher);
  151. factory->setPeerAnnounceStorage(peerAnnounceStorage);
  152. factory->setTokenTracker(tokenTracker);
  153. factory->setLocalNode(localNode);
  154. // assign them into DHTRegistry
  155. DHTRegistry::getMutableData().localNode = localNode;
  156. DHTRegistry::getMutableData().routingTable = routingTable;
  157. DHTRegistry::getMutableData().taskQueue = taskQueue;
  158. DHTRegistry::getMutableData().taskFactory = taskFactory;
  159. DHTRegistry::getMutableData().peerAnnounceStorage = peerAnnounceStorage;
  160. DHTRegistry::getMutableData().tokenTracker = tokenTracker;
  161. DHTRegistry::getMutableData().messageDispatcher = dispatcher;
  162. DHTRegistry::getMutableData().messageReceiver = receiver;
  163. DHTRegistry::getMutableData().messageFactory = factory;
  164. // add deserialized nodes to routing table
  165. const std::vector<SharedHandle<DHTNode> >& desnodes =
  166. deserializer.getNodes();
  167. for(std::vector<SharedHandle<DHTNode> >::const_iterator i =
  168. desnodes.begin(), eoi = desnodes.end(); i != eoi; ++i) {
  169. routingTable->addNode(*i);
  170. }
  171. if(!desnodes.empty() &&
  172. deserializer.getSerializedTime().
  173. difference() >= DHT_BUCKET_REFRESH_INTERVAL) {
  174. SharedHandle<DHTBucketRefreshTask> task
  175. (static_pointer_cast<DHTBucketRefreshTask>
  176. (taskFactory->createBucketRefreshTask()));
  177. task->setForceRefresh(true);
  178. taskQueue->addPeriodicTask1(task);
  179. }
  180. if(!e->getOption()->get(PREF_DHT_ENTRY_POINT_HOST).empty()) {
  181. {
  182. std::pair<std::string, uint16_t> addr
  183. (e->getOption()->get(PREF_DHT_ENTRY_POINT_HOST),
  184. e->getOption()->getAsInt(PREF_DHT_ENTRY_POINT_PORT));
  185. std::vector<std::pair<std::string, uint16_t> > entryPoints;
  186. entryPoints.push_back(addr);
  187. DHTEntryPointNameResolveCommand* command =
  188. new DHTEntryPointNameResolveCommand(e->newCUID(), e, entryPoints);
  189. command->setBootstrapEnabled(true);
  190. command->setTaskQueue(taskQueue);
  191. command->setTaskFactory(taskFactory);
  192. command->setRoutingTable(routingTable);
  193. command->setLocalNode(localNode);
  194. tempCommands.push_back(command);
  195. }
  196. } else {
  197. _logger->info("No DHT entry point specified.");
  198. }
  199. {
  200. DHTInteractionCommand* command =
  201. new DHTInteractionCommand(e->newCUID(), e);
  202. command->setMessageDispatcher(dispatcher);
  203. command->setMessageReceiver(receiver);
  204. command->setTaskQueue(taskQueue);
  205. command->setReadCheckSocket(connection->getSocket());
  206. tempCommands.push_back(command);
  207. }
  208. {
  209. DHTTokenUpdateCommand* command =
  210. new DHTTokenUpdateCommand(e->newCUID(), e, DHT_TOKEN_UPDATE_INTERVAL);
  211. command->setTokenTracker(tokenTracker);
  212. tempCommands.push_back(command);
  213. }
  214. {
  215. DHTBucketRefreshCommand* command =
  216. new DHTBucketRefreshCommand(e->newCUID(), e,
  217. DHT_BUCKET_REFRESH_CHECK_INTERVAL);
  218. command->setTaskQueue(taskQueue);
  219. command->setRoutingTable(routingTable);
  220. command->setTaskFactory(taskFactory);
  221. tempCommands.push_back(command);
  222. }
  223. {
  224. DHTPeerAnnounceCommand* command =
  225. new DHTPeerAnnounceCommand(e->newCUID(), e,
  226. DHT_PEER_ANNOUNCE_CHECK_INTERVAL);
  227. command->setPeerAnnounceStorage(peerAnnounceStorage);
  228. tempCommands.push_back(command);
  229. }
  230. {
  231. DHTAutoSaveCommand* command =
  232. new DHTAutoSaveCommand(e->newCUID(), e, 30*60);
  233. command->setLocalNode(localNode);
  234. command->setRoutingTable(routingTable);
  235. tempCommands.push_back(command);
  236. }
  237. _initialized = true;
  238. commands.insert(commands.end(), tempCommands.begin(), tempCommands.end());
  239. } catch(RecoverableException& e) {
  240. _logger->error("Exception caught while initializing DHT functionality. DHT is disabled.", e);
  241. DHTRegistry::clearData();
  242. std::for_each(tempCommands.begin(), tempCommands.end(), Deleter());
  243. }
  244. }
  245. bool DHTSetup::initialized()
  246. {
  247. return _initialized;
  248. }
  249. } // namespace aria2