DHTSetup.cc 9.9 KB

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