DefaultBtAnnounce.cc 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  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 "DefaultBtAnnounce.h"
  36. #include "LogFactory.h"
  37. #include "Logger.h"
  38. #include "PeerListProcessor.h"
  39. #include "util.h"
  40. #include "prefs.h"
  41. #include "DlAbortEx.h"
  42. #include "message.h"
  43. #include "SimpleRandomizer.h"
  44. #include "DownloadContext.h"
  45. #include "PieceStorage.h"
  46. #include "BtRuntime.h"
  47. #include "PeerStorage.h"
  48. #include "Peer.h"
  49. #include "Option.h"
  50. #include "StringFormat.h"
  51. #include "A2STR.h"
  52. #include "Request.h"
  53. #include "bencode.h"
  54. #include "bittorrent_helper.h"
  55. #include "wallclock.h"
  56. namespace aria2 {
  57. DefaultBtAnnounce::DefaultBtAnnounce
  58. (const SharedHandle<DownloadContext>& downloadContext,
  59. const Option* option):
  60. _downloadContext(downloadContext),
  61. trackers(0),
  62. prevAnnounceTimer(0),
  63. interval(DEFAULT_ANNOUNCE_INTERVAL),
  64. minInterval(DEFAULT_ANNOUNCE_INTERVAL),
  65. _userDefinedInterval(0),
  66. complete(0),
  67. incomplete(0),
  68. announceList(downloadContext->getAttribute(bittorrent::BITTORRENT)[bittorrent::ANNOUNCE_LIST]),
  69. option(option),
  70. logger(LogFactory::getInstance()),
  71. _randomizer(SimpleRandomizer::getInstance())
  72. {}
  73. DefaultBtAnnounce::~DefaultBtAnnounce() {
  74. }
  75. bool DefaultBtAnnounce::isDefaultAnnounceReady() {
  76. return
  77. (trackers == 0 &&
  78. prevAnnounceTimer.
  79. difference(global::wallclock) >= (_userDefinedInterval==0?
  80. minInterval:_userDefinedInterval) &&
  81. !announceList.allTiersFailed());
  82. }
  83. bool DefaultBtAnnounce::isStoppedAnnounceReady() {
  84. return (trackers == 0 &&
  85. btRuntime->isHalt() &&
  86. announceList.countStoppedAllowedTier());
  87. }
  88. bool DefaultBtAnnounce::isCompletedAnnounceReady() {
  89. return (trackers == 0 &&
  90. pieceStorage->allDownloadFinished() &&
  91. announceList.countCompletedAllowedTier());
  92. }
  93. bool DefaultBtAnnounce::isAnnounceReady() {
  94. return
  95. isStoppedAnnounceReady() ||
  96. isCompletedAnnounceReady() ||
  97. isDefaultAnnounceReady();
  98. }
  99. static bool uriHasQuery(const std::string& uri)
  100. {
  101. Request req;
  102. req.setUri(uri);
  103. return !req.getQuery().empty();
  104. }
  105. std::string DefaultBtAnnounce::getAnnounceUrl() {
  106. if(isStoppedAnnounceReady()) {
  107. if(!announceList.currentTierAcceptsStoppedEvent()) {
  108. announceList.moveToStoppedAllowedTier();
  109. }
  110. announceList.setEvent(AnnounceTier::STOPPED);
  111. } else if(isCompletedAnnounceReady()) {
  112. if(!announceList.currentTierAcceptsCompletedEvent()) {
  113. announceList.moveToCompletedAllowedTier();
  114. }
  115. announceList.setEvent(AnnounceTier::COMPLETED);
  116. } else if(isDefaultAnnounceReady()) {
  117. // If download completed before "started" event is sent to a tracker,
  118. // we change the event to something else to prevent us from
  119. // sending "completed" event.
  120. if(pieceStorage->allDownloadFinished() &&
  121. announceList.getEvent() == AnnounceTier::STARTED) {
  122. announceList.setEvent(AnnounceTier::STARTED_AFTER_COMPLETION);
  123. }
  124. } else {
  125. return A2STR::NIL;
  126. }
  127. unsigned int numWant = 50;
  128. if(!btRuntime->lessThanMinPeers() || btRuntime->isHalt()) {
  129. numWant = 0;
  130. }
  131. TransferStat stat = peerStorage->calculateStat();
  132. uint64_t left =
  133. pieceStorage->getTotalLength()-pieceStorage->getCompletedLength();
  134. std::string uri = announceList.getAnnounce();
  135. uri += uriHasQuery(uri) ? "&" : "?";
  136. uri += "info_hash=";
  137. uri += util::torrentPercentEncode(bittorrent::getInfoHash(_downloadContext),
  138. INFO_HASH_LENGTH);
  139. uri += "&peer_id=";
  140. uri += util::torrentPercentEncode(bittorrent::getStaticPeerId(),
  141. PEER_ID_LENGTH);
  142. uri += "&uploaded=";
  143. uri += util::uitos(stat.getSessionUploadLength());
  144. uri += "&downloaded=";
  145. uri += util::uitos(stat.getSessionDownloadLength());
  146. uri += "&left=";
  147. uri += util::uitos(left);
  148. uri += "&compact=1";
  149. uri += "&key=";
  150. // Use last 8 bytes of peer ID as a key
  151. size_t keyLen = 8;
  152. uri += util::torrentPercentEncode
  153. (bittorrent::getStaticPeerId()+PEER_ID_LENGTH-keyLen, keyLen);
  154. uri += "&numwant=";
  155. uri += util::uitos(numWant);
  156. uri += "&no_peer_id=1";
  157. if(btRuntime->getListenPort() > 0) {
  158. uri += "&port=";
  159. uri += util::uitos(btRuntime->getListenPort());
  160. }
  161. std::string event = announceList.getEventString();
  162. if(!event.empty()) {
  163. uri += "&event=";
  164. uri += event;
  165. }
  166. if(!trackerId.empty()) {
  167. uri += "&trackerid="+util::torrentPercentEncode(trackerId);
  168. }
  169. if(option->getAsBool(PREF_BT_REQUIRE_CRYPTO)) {
  170. uri += "&requirecrypto=1";
  171. } else {
  172. uri += "&supportcrypto=1";
  173. }
  174. if(!option->blank(PREF_BT_EXTERNAL_IP)) {
  175. uri += "&ip=";
  176. uri += option->get(PREF_BT_EXTERNAL_IP);
  177. }
  178. return uri;
  179. }
  180. void DefaultBtAnnounce::announceStart() {
  181. trackers++;
  182. }
  183. void DefaultBtAnnounce::announceSuccess() {
  184. trackers = 0;
  185. announceList.announceSuccess();
  186. }
  187. void DefaultBtAnnounce::announceFailure() {
  188. trackers = 0;
  189. announceList.announceFailure();
  190. }
  191. bool DefaultBtAnnounce::isAllAnnounceFailed() {
  192. return announceList.allTiersFailed();
  193. }
  194. void DefaultBtAnnounce::resetAnnounce() {
  195. prevAnnounceTimer = global::wallclock;
  196. announceList.resetTier();
  197. }
  198. void
  199. DefaultBtAnnounce::processAnnounceResponse(const unsigned char* trackerResponse,
  200. size_t trackerResponseLength)
  201. {
  202. if(logger->debug()) {
  203. logger->debug("Now processing tracker response.");
  204. }
  205. const BDE dict =
  206. bencode::decode(trackerResponse, trackerResponseLength);
  207. if(!dict.isDict()) {
  208. throw DL_ABORT_EX(MSG_NULL_TRACKER_RESPONSE);
  209. }
  210. const BDE& failure = dict[BtAnnounce::FAILURE_REASON];
  211. if(failure.isString()) {
  212. throw DL_ABORT_EX
  213. (StringFormat(EX_TRACKER_FAILURE, failure.s().c_str()).str());
  214. }
  215. const BDE& warn = dict[BtAnnounce::WARNING_MESSAGE];
  216. if(warn.isString()) {
  217. logger->warn(MSG_TRACKER_WARNING_MESSAGE, warn.s().c_str());
  218. }
  219. const BDE& tid = dict[BtAnnounce::TRACKER_ID];
  220. if(tid.isString()) {
  221. trackerId = tid.s();
  222. if(logger->debug()) {
  223. logger->debug("Tracker ID:%s", trackerId.c_str());
  224. }
  225. }
  226. const BDE& ival = dict[BtAnnounce::INTERVAL];
  227. if(ival.isInteger() && ival.i() > 0) {
  228. interval = ival.i();
  229. if(logger->debug()) {
  230. logger->debug("Interval:%d", interval);
  231. }
  232. }
  233. const BDE& mival = dict[BtAnnounce::MIN_INTERVAL];
  234. if(mival.isInteger() && mival.i() > 0) {
  235. minInterval = mival.i();
  236. if(logger->debug()) {
  237. logger->debug("Min interval:%d", minInterval);
  238. }
  239. if(minInterval > interval) {
  240. minInterval = interval;
  241. }
  242. } else {
  243. // Use interval as a minInterval if minInterval is not supplied.
  244. minInterval = interval;
  245. }
  246. const BDE& comp = dict[BtAnnounce::COMPLETE];
  247. if(comp.isInteger()) {
  248. complete = comp.i();
  249. if(logger->debug()) {
  250. logger->debug("Complete:%d", complete);
  251. }
  252. }
  253. const BDE& incomp = dict[BtAnnounce::INCOMPLETE];
  254. if(incomp.isInteger()) {
  255. incomplete = incomp.i();
  256. if(logger->debug()) {
  257. logger->debug("Incomplete:%d", incomplete);
  258. }
  259. }
  260. const BDE& peerData = dict[BtAnnounce::PEERS];
  261. if(peerData.isNone()) {
  262. logger->info(MSG_NO_PEER_LIST_RECEIVED);
  263. } else {
  264. if(!btRuntime->isHalt() && btRuntime->lessThanMinPeers()) {
  265. std::vector<SharedHandle<Peer> > peers;
  266. PeerListProcessor().extractPeer(peerData, std::back_inserter(peers));
  267. peerStorage->addPeer(peers);
  268. }
  269. }
  270. }
  271. bool DefaultBtAnnounce::noMoreAnnounce() {
  272. return (trackers == 0 &&
  273. btRuntime->isHalt() &&
  274. !announceList.countStoppedAllowedTier());
  275. }
  276. void DefaultBtAnnounce::shuffleAnnounce() {
  277. announceList.shuffle();
  278. }
  279. void DefaultBtAnnounce::setRandomizer(const RandomizerHandle& randomizer)
  280. {
  281. _randomizer = randomizer;
  282. }
  283. void DefaultBtAnnounce::setBtRuntime(const BtRuntimeHandle& btRuntime)
  284. {
  285. this->btRuntime = btRuntime;
  286. }
  287. void DefaultBtAnnounce::setPieceStorage(const PieceStorageHandle& pieceStorage)
  288. {
  289. this->pieceStorage = pieceStorage;
  290. }
  291. void DefaultBtAnnounce::setPeerStorage(const PeerStorageHandle& peerStorage)
  292. {
  293. this->peerStorage = peerStorage;
  294. }
  295. void DefaultBtAnnounce::overrideMinInterval(time_t interval)
  296. {
  297. minInterval = interval;
  298. }
  299. } // namespace aria2