DHTSetup.cc 9.0 KB

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