DefaultBtAnnounce.cc 10 KB

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