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 "BtRegistry.h"
  37. #include "LogFactory.h"
  38. #include "Logger.h"
  39. #include "MetaFileUtil.h"
  40. #include "Dictionary.h"
  41. #include "List.h"
  42. #include "Data.h"
  43. #include "DelegatingPeerListProcessor.h"
  44. #include "Util.h"
  45. #include "prefs.h"
  46. #include "DlAbortEx.h"
  47. #include "message.h"
  48. #include "SimpleRandomizer.h"
  49. #include "BtContext.h"
  50. #include "PieceStorage.h"
  51. #include "BtRuntime.h"
  52. #include "PeerStorage.h"
  53. #include "Peer.h"
  54. #include "Option.h"
  55. #include "StringFormat.h"
  56. #include "A2STR.h"
  57. namespace aria2 {
  58. DefaultBtAnnounce::DefaultBtAnnounce(const BtContextHandle& btContext,
  59. const Option* option):
  60. btContext(btContext),
  61. trackers(0),
  62. interval(DEFAULT_ANNOUNCE_INTERVAL),
  63. minInterval(DEFAULT_ANNOUNCE_INTERVAL),
  64. complete(0),
  65. incomplete(0),
  66. announceList(btContext->getAnnounceTiers()),
  67. option(option),
  68. logger(LogFactory::getInstance()),
  69. _randomizer(SimpleRandomizer::getInstance()),
  70. btRuntime(BT_RUNTIME(btContext)),
  71. pieceStorage(PIECE_STORAGE(btContext)),
  72. peerStorage(PEER_STORAGE(btContext))
  73. {
  74. prevAnnounceTime.setTimeInSec(0);
  75. generateKey();
  76. }
  77. DefaultBtAnnounce::~DefaultBtAnnounce() {
  78. }
  79. void DefaultBtAnnounce::generateKey()
  80. {
  81. key = Util::randomAlpha(8, _randomizer);
  82. }
  83. bool DefaultBtAnnounce::isDefaultAnnounceReady() {
  84. return (trackers == 0 && prevAnnounceTime.elapsed(minInterval) &&
  85. !announceList.allTiersFailed());
  86. }
  87. bool DefaultBtAnnounce::isStoppedAnnounceReady() {
  88. return (trackers == 0 &&
  89. btRuntime->isHalt() &&
  90. announceList.countStoppedAllowedTier());
  91. }
  92. bool DefaultBtAnnounce::isCompletedAnnounceReady() {
  93. return (trackers == 0 &&
  94. pieceStorage->allDownloadFinished() &&
  95. announceList.countCompletedAllowedTier());
  96. }
  97. bool DefaultBtAnnounce::isAnnounceReady() {
  98. return
  99. isStoppedAnnounceReady() ||
  100. isCompletedAnnounceReady() ||
  101. isDefaultAnnounceReady();
  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 = pieceStorage->getTotalLength()-pieceStorage->getCompletedLength();
  131. if(left < 0) {
  132. left = 0;
  133. }
  134. std::string url = announceList.getAnnounce()+
  135. "?info_hash="+Util::torrentUrlencode(btContext->getInfoHash(),
  136. btContext->getInfoHashLength())+
  137. "&peer_id="+Util::torrentUrlencode(btContext->getPeerId(), 20)+
  138. "&uploaded="+Util::uitos(stat.getSessionUploadLength())+
  139. "&downloaded="+Util::uitos(stat.getSessionDownloadLength())+
  140. "&left="+Util::uitos(left)+
  141. "&compact=1"+
  142. "&key="+key+
  143. "&numwant="+Util::uitos(numWant)+
  144. "&no_peer_id=1";
  145. if(btRuntime->getListenPort() > 0) {
  146. url += "&port="+Util::uitos(btRuntime->getListenPort());
  147. }
  148. std::string event = announceList.getEventString();
  149. if(!event.empty()) {
  150. url += "&event="+event;
  151. }
  152. if(!trackerId.empty()) {
  153. url += "&trackerid="+Util::torrentUrlencode(trackerId);
  154. }
  155. if(option->getAsBool(PREF_BT_REQUIRE_CRYPTO)) {
  156. url += "&requirecrypto=1";
  157. } else {
  158. url += "&supportcrypto=1";
  159. }
  160. return url;
  161. }
  162. void DefaultBtAnnounce::announceStart() {
  163. trackers++;
  164. }
  165. void DefaultBtAnnounce::announceSuccess() {
  166. trackers = 0;
  167. announceList.announceSuccess();
  168. }
  169. void DefaultBtAnnounce::announceFailure() {
  170. trackers = 0;
  171. announceList.announceFailure();
  172. }
  173. bool DefaultBtAnnounce::isAllAnnounceFailed() {
  174. return announceList.allTiersFailed();
  175. }
  176. void DefaultBtAnnounce::resetAnnounce() {
  177. prevAnnounceTime.reset();
  178. announceList.resetTier();
  179. }
  180. void
  181. DefaultBtAnnounce::processAnnounceResponse(const unsigned char* trackerResponse,
  182. size_t trackerResponseLength)
  183. {
  184. SharedHandle<MetaEntry> entry(MetaFileUtil::bdecoding(trackerResponse,
  185. trackerResponseLength));
  186. const Dictionary* response = dynamic_cast<const Dictionary*>(entry.get());
  187. if(!response) {
  188. throw DlAbortEx(MSG_NULL_TRACKER_RESPONSE);
  189. }
  190. const Data* failureReasonData =
  191. dynamic_cast<const Data*>(response->get(BtAnnounce::FAILURE_REASON));
  192. if(failureReasonData) {
  193. throw DlAbortEx
  194. (StringFormat(EX_TRACKER_FAILURE,
  195. failureReasonData->toString().c_str()).str());
  196. }
  197. const Data* warningMessageData =
  198. dynamic_cast<const Data*>(response->get(BtAnnounce::WARNING_MESSAGE));
  199. if(warningMessageData) {
  200. logger->warn(MSG_TRACKER_WARNING_MESSAGE,
  201. warningMessageData->toString().c_str());
  202. }
  203. const Data* trackerIdData =
  204. dynamic_cast<const Data*>(response->get(BtAnnounce::TRACKER_ID));
  205. if(trackerIdData) {
  206. trackerId = trackerIdData->toString();
  207. logger->debug("Tracker ID:%s", trackerId.c_str());
  208. }
  209. const Data* intervalData =
  210. dynamic_cast<const Data*>(response->get(BtAnnounce::INTERVAL));
  211. if(intervalData) {
  212. time_t t = intervalData->toInt();
  213. if(t > 0) {
  214. interval = intervalData->toInt();
  215. logger->debug("Interval:%d", interval);
  216. }
  217. }
  218. const Data* minIntervalData =
  219. dynamic_cast<const Data*>(response->get(BtAnnounce::MIN_INTERVAL));
  220. if(minIntervalData) {
  221. time_t t = minIntervalData->toInt();
  222. if(t > 0) {
  223. minInterval = minIntervalData->toInt();
  224. logger->debug("Min interval:%d", minInterval);
  225. }
  226. if(minInterval > interval) {
  227. minInterval = interval;
  228. }
  229. } else {
  230. // Use interval as a minInterval if minInterval is not supplied.
  231. minInterval = interval;
  232. }
  233. const Data* completeData =
  234. dynamic_cast<const Data*>(response->get(BtAnnounce::COMPLETE));
  235. if(completeData) {
  236. complete = completeData->toInt();
  237. logger->debug("Complete:%d", complete);
  238. }
  239. const Data* incompleteData =
  240. dynamic_cast<const Data*>(response->get(BtAnnounce::INCOMPLETE));
  241. if(incompleteData) {
  242. incomplete = incompleteData->toInt();
  243. logger->debug("Incomplete:%d", incomplete);
  244. }
  245. const MetaEntry* peersEntry = response->get(BtAnnounce::PEERS);
  246. if(peersEntry &&
  247. !btRuntime->isHalt() &&
  248. btRuntime->lessThanMinPeers()) {
  249. DelegatingPeerListProcessor proc;
  250. std::deque<SharedHandle<Peer> > peers;
  251. proc.extractPeer(peers, peersEntry);
  252. peerStorage->addPeer(peers);
  253. }
  254. if(!peersEntry) {
  255. logger->info(MSG_NO_PEER_LIST_RECEIVED);
  256. }
  257. }
  258. bool DefaultBtAnnounce::noMoreAnnounce() {
  259. return (trackers == 0 &&
  260. btRuntime->isHalt() &&
  261. !announceList.countStoppedAllowedTier());
  262. }
  263. void DefaultBtAnnounce::shuffleAnnounce() {
  264. announceList.shuffle();
  265. }
  266. void DefaultBtAnnounce::setRandomizer(const RandomizerHandle& randomizer)
  267. {
  268. _randomizer = randomizer;
  269. }
  270. void DefaultBtAnnounce::setBtRuntime(const BtRuntimeHandle& btRuntime)
  271. {
  272. this->btRuntime = btRuntime;
  273. }
  274. BtRuntimeHandle DefaultBtAnnounce::getBtRuntime() const
  275. {
  276. return btRuntime;
  277. }
  278. void DefaultBtAnnounce::setPieceStorage(const PieceStorageHandle& pieceStorage)
  279. {
  280. this->pieceStorage = pieceStorage;
  281. }
  282. PieceStorageHandle DefaultBtAnnounce::getPieceStorage() const
  283. {
  284. return pieceStorage;
  285. }
  286. void DefaultBtAnnounce::setPeerStorage(const PeerStorageHandle& peerStorage)
  287. {
  288. this->peerStorage = peerStorage;
  289. }
  290. PeerStorageHandle DefaultBtAnnounce::getPeerStorage() const
  291. {
  292. return peerStorage;
  293. }
  294. } // namespace aria2