TrackerWatcherCommand.cc 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  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 "TrackerWatcherCommand.h"
  36. #include <sstream>
  37. #include "DownloadEngine.h"
  38. #include "BtAnnounce.h"
  39. #include "BtRuntime.h"
  40. #include "PieceStorage.h"
  41. #include "PeerStorage.h"
  42. #include "Peer.h"
  43. #include "prefs.h"
  44. #include "message.h"
  45. #include "ByteArrayDiskWriterFactory.h"
  46. #include "RecoverableException.h"
  47. #include "PeerInitiateConnectionCommand.h"
  48. #include "DiskAdaptor.h"
  49. #include "FileEntry.h"
  50. #include "RequestGroup.h"
  51. #include "Option.h"
  52. #include "DlAbortEx.h"
  53. #include "Logger.h"
  54. #include "LogFactory.h"
  55. #include "A2STR.h"
  56. #include "SocketCore.h"
  57. #include "Request.h"
  58. #include "AnnounceTier.h"
  59. #include "DownloadContext.h"
  60. #include "bittorrent_helper.h"
  61. #include "a2functional.h"
  62. #include "util.h"
  63. #include "fmt.h"
  64. namespace aria2 {
  65. TrackerWatcherCommand::TrackerWatcherCommand
  66. (cuid_t cuid, RequestGroup* requestGroup, DownloadEngine* e)
  67. : Command(cuid),
  68. requestGroup_(requestGroup),
  69. e_(e)
  70. {
  71. requestGroup_->increaseNumCommand();
  72. }
  73. TrackerWatcherCommand::~TrackerWatcherCommand()
  74. {
  75. requestGroup_->decreaseNumCommand();
  76. }
  77. bool TrackerWatcherCommand::execute() {
  78. if(requestGroup_->isForceHaltRequested()) {
  79. if(!trackerRequestGroup_) {
  80. return true;
  81. } else if(trackerRequestGroup_->getNumCommand() == 0 ||
  82. trackerRequestGroup_->downloadFinished()) {
  83. return true;
  84. } else {
  85. trackerRequestGroup_->setForceHaltRequested(true);
  86. e_->setRefreshInterval(0);
  87. e_->addCommand(this);
  88. return false;
  89. }
  90. }
  91. if(btAnnounce_->noMoreAnnounce()) {
  92. A2_LOG_DEBUG("no more announce");
  93. return true;
  94. }
  95. if(!trackerRequestGroup_) {
  96. trackerRequestGroup_ = createAnnounce();
  97. if(trackerRequestGroup_) {
  98. try {
  99. std::vector<Command*>* commands = new std::vector<Command*>();
  100. auto_delete_container<std::vector<Command*> > commandsDel(commands);
  101. trackerRequestGroup_->createInitialCommand(*commands, e_);
  102. e_->addCommand(*commands);
  103. commands->clear();
  104. A2_LOG_DEBUG("added tracker request command");
  105. } catch(RecoverableException& ex) {
  106. A2_LOG_ERROR_EX(EX_EXCEPTION_CAUGHT, ex);
  107. }
  108. }
  109. } else if(trackerRequestGroup_->getNumCommand() == 0) {
  110. // We really want to make sure that tracker request has finished
  111. // by checking getNumCommand() == 0. Because we reset
  112. // trackerRequestGroup_, if it is still used in other Command, we
  113. // will get Segmentation fault.
  114. if(trackerRequestGroup_->downloadFinished()) {
  115. try {
  116. std::string trackerResponse = getTrackerResponse(trackerRequestGroup_);
  117. processTrackerResponse(trackerResponse);
  118. btAnnounce_->announceSuccess();
  119. btAnnounce_->resetAnnounce();
  120. } catch(RecoverableException& ex) {
  121. A2_LOG_ERROR_EX(EX_EXCEPTION_CAUGHT, ex);
  122. btAnnounce_->announceFailure();
  123. if(btAnnounce_->isAllAnnounceFailed()) {
  124. btAnnounce_->resetAnnounce();
  125. }
  126. }
  127. trackerRequestGroup_.reset();
  128. } else {
  129. // handle errors here
  130. btAnnounce_->announceFailure(); // inside it, trackers = 0.
  131. trackerRequestGroup_.reset();
  132. if(btAnnounce_->isAllAnnounceFailed()) {
  133. btAnnounce_->resetAnnounce();
  134. }
  135. }
  136. }
  137. e_->addCommand(this);
  138. return false;
  139. }
  140. std::string TrackerWatcherCommand::getTrackerResponse
  141. (const SharedHandle<RequestGroup>& requestGroup)
  142. {
  143. std::stringstream strm;
  144. unsigned char data[2048];
  145. requestGroup->getPieceStorage()->getDiskAdaptor()->openFile();
  146. while(1) {
  147. ssize_t dataLength = requestGroup->getPieceStorage()->
  148. getDiskAdaptor()->readData(data, sizeof(data), strm.tellp());
  149. if(dataLength == 0) {
  150. break;
  151. }
  152. strm.write(reinterpret_cast<const char*>(data), dataLength);
  153. }
  154. return strm.str();
  155. }
  156. // TODO we have to deal with the exception thrown By BtAnnounce
  157. void TrackerWatcherCommand::processTrackerResponse
  158. (const std::string& trackerResponse)
  159. {
  160. btAnnounce_->processAnnounceResponse
  161. (reinterpret_cast<const unsigned char*>(trackerResponse.c_str()),
  162. trackerResponse.size());
  163. while(!btRuntime_->isHalt() && btRuntime_->lessThanMinPeers()) {
  164. if(!peerStorage_->isPeerAvailable()) {
  165. break;
  166. }
  167. cuid_t ncuid = e_->newCUID();
  168. SharedHandle<Peer> peer = peerStorage_->checkoutPeer(ncuid);
  169. // sanity check
  170. if(!peer) {
  171. break;
  172. }
  173. PeerInitiateConnectionCommand* command;
  174. command = new PeerInitiateConnectionCommand(ncuid, requestGroup_, peer, e_,
  175. btRuntime_);
  176. command->setPeerStorage(peerStorage_);
  177. command->setPieceStorage(pieceStorage_);
  178. e_->addCommand(command);
  179. A2_LOG_DEBUG(fmt("CUID#%" PRId64 " - Adding new command CUID#%" PRId64 "",
  180. getCuid(), peer->usedBy()));
  181. }
  182. }
  183. SharedHandle<RequestGroup> TrackerWatcherCommand::createAnnounce() {
  184. SharedHandle<RequestGroup> rg;
  185. if(btAnnounce_->isAnnounceReady()) {
  186. rg = createRequestGroup(btAnnounce_->getAnnounceUrl());
  187. btAnnounce_->announceStart(); // inside it, trackers++.
  188. }
  189. return rg;
  190. }
  191. namespace {
  192. bool backupTrackerIsAvailable
  193. (const SharedHandle<DownloadContext>& context)
  194. {
  195. SharedHandle<TorrentAttribute> torrentAttrs =
  196. bittorrent::getTorrentAttrs(context);
  197. if(torrentAttrs->announceList.size() >= 2) {
  198. return true;
  199. }
  200. if(torrentAttrs->announceList.empty()) {
  201. return false;
  202. }
  203. if(torrentAttrs->announceList[0].size() >= 2) {
  204. return true;
  205. } else {
  206. return false;
  207. }
  208. }
  209. } // namespace
  210. SharedHandle<RequestGroup>
  211. TrackerWatcherCommand::createRequestGroup(const std::string& uri)
  212. {
  213. std::vector<std::string> uris;
  214. uris.push_back(uri);
  215. SharedHandle<Option> option = util::copy(getOption());
  216. SharedHandle<RequestGroup> rg(new RequestGroup(GroupId::create(), option));
  217. if(backupTrackerIsAvailable(requestGroup_->getDownloadContext())) {
  218. A2_LOG_DEBUG("This is multi-tracker announce.");
  219. } else {
  220. A2_LOG_DEBUG("This is single-tracker announce.");
  221. }
  222. rg->setNumConcurrentCommand(1);
  223. // If backup tracker is available, try 2 times for each tracker
  224. // and if they all fails, then try next one.
  225. option->put(PREF_MAX_TRIES, "2");
  226. // TODO When dry-run mode becomes available in BitTorrent, set
  227. // PREF_DRY_RUN=false too.
  228. option->put(PREF_USE_HEAD, A2_V_FALSE);
  229. // Setting tracker timeouts
  230. rg->setTimeout(option->getAsInt(PREF_BT_TRACKER_TIMEOUT));
  231. option->put(PREF_CONNECT_TIMEOUT,
  232. option->get(PREF_BT_TRACKER_CONNECT_TIMEOUT));
  233. option->put(PREF_REUSE_URI, A2_V_FALSE);
  234. option->put(PREF_SELECT_LEAST_USED_HOST, A2_V_FALSE);
  235. SharedHandle<DownloadContext> dctx
  236. (new DownloadContext(option->getAsInt(PREF_PIECE_LENGTH),
  237. 0,
  238. "[tracker.announce]"));
  239. dctx->getFileEntries().front()->setUris(uris);
  240. rg->setDownloadContext(dctx);
  241. SharedHandle<DiskWriterFactory> dwf(new ByteArrayDiskWriterFactory());
  242. rg->setDiskWriterFactory(dwf);
  243. rg->setFileAllocationEnabled(false);
  244. rg->setPreLocalFileCheckEnabled(false);
  245. // Clearing pre- and post handler is not needed because the
  246. // RequestGroup is not handled by RequestGroupMan.
  247. rg->clearPreDownloadHandler();
  248. rg->clearPostDownloadHandler();
  249. dctx->setAcceptMetalink(false);
  250. A2_LOG_INFO(fmt("Creating tracker request group GID#%s",
  251. GroupId::toHex(rg->getGID()).c_str()));
  252. return rg;
  253. }
  254. void TrackerWatcherCommand::setBtRuntime
  255. (const SharedHandle<BtRuntime>& btRuntime)
  256. {
  257. btRuntime_ = btRuntime;
  258. }
  259. void TrackerWatcherCommand::setPeerStorage
  260. (const SharedHandle<PeerStorage>& peerStorage)
  261. {
  262. peerStorage_ = peerStorage;
  263. }
  264. void TrackerWatcherCommand::setPieceStorage
  265. (const SharedHandle<PieceStorage>& pieceStorage)
  266. {
  267. pieceStorage_ = pieceStorage;
  268. }
  269. void TrackerWatcherCommand::setBtAnnounce
  270. (const SharedHandle<BtAnnounce>& btAnnounce)
  271. {
  272. btAnnounce_ = btAnnounce;
  273. }
  274. const SharedHandle<Option>& TrackerWatcherCommand::getOption() const
  275. {
  276. return requestGroup_->getOption();
  277. }
  278. } // namespace aria2