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