DHTSetup.cc 9.5 KB

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