DHTSetup.cc 11 KB

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