DefaultBtAnnounce.cc 8.7 KB

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