DefaultBtAnnounce.cc 9.4 KB

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