DefaultBtAnnounce.cc 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  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. 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. complete(0),
  62. incomplete(0),
  63. announceList(btContext->getAnnounceTiers()),
  64. option(option),
  65. logger(LogFactory::getInstance()),
  66. _randomizer(SimpleRandomizer::getInstance()),
  67. btRuntime(BT_RUNTIME(btContext)),
  68. pieceStorage(PIECE_STORAGE(btContext)),
  69. peerStorage(PEER_STORAGE(btContext))
  70. {
  71. prevAnnounceTime.setTimeInSec(0);
  72. generateKey();
  73. }
  74. DefaultBtAnnounce::~DefaultBtAnnounce() {
  75. }
  76. void DefaultBtAnnounce::generateKey()
  77. {
  78. key = Util::randomAlpha(8, _randomizer);
  79. }
  80. bool DefaultBtAnnounce::isDefaultAnnounceReady() {
  81. return (trackers == 0 && prevAnnounceTime.elapsed(minInterval) &&
  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. std::string DefaultBtAnnounce::getAnnounceUrl() {
  101. if(isStoppedAnnounceReady()) {
  102. if(!announceList.currentTierAcceptsStoppedEvent()) {
  103. announceList.moveToStoppedAllowedTier();
  104. }
  105. announceList.setEvent(AnnounceTier::STOPPED);
  106. } else if(isCompletedAnnounceReady()) {
  107. if(!announceList.currentTierAcceptsCompletedEvent()) {
  108. announceList.moveToCompletedAllowedTier();
  109. }
  110. announceList.setEvent(AnnounceTier::COMPLETED);
  111. } else if(isDefaultAnnounceReady()) {
  112. // If download completed before "started" event is sent to a tracker,
  113. // we change the event to something else to prevent us from
  114. // sending "completed" event.
  115. if(pieceStorage->allDownloadFinished() &&
  116. announceList.getEvent() == AnnounceTier::STARTED) {
  117. announceList.setEvent(AnnounceTier::STARTED_AFTER_COMPLETION);
  118. }
  119. } else {
  120. return "";
  121. }
  122. int32_t numWant = 50;
  123. if(!btRuntime->lessThanEqMinPeer() ||
  124. btRuntime->isHalt()) {
  125. numWant = 0;
  126. }
  127. TransferStat stat = peerStorage->calculateStat();
  128. int64_t left = pieceStorage->getTotalLength()-pieceStorage->getCompletedLength();
  129. if(left < 0) {
  130. left = 0;
  131. }
  132. std::string url = announceList.getAnnounce()+"?"+
  133. "info_hash="+Util::torrentUrlencode(btContext->getInfoHash(),
  134. btContext->getInfoHashLength())+"&"+
  135. "peer_id="+Util::torrentUrlencode(btContext->getPeerId(), 20)+"&"+
  136. "uploaded="+Util::llitos(stat.getSessionUploadLength())+"&"+
  137. "downloaded="+Util::llitos(stat.getSessionDownloadLength())+"&"+
  138. "left="+Util::llitos(left)+"&"+
  139. "compact=1"+"&"+
  140. "key="+key+"&"+
  141. "numwant="+Util::itos(numWant)+"&"+
  142. "no_peer_id=1";
  143. if(btRuntime->getListenPort() > 0) {
  144. url += std::string("&")+"port="+Util::itos(btRuntime->getListenPort());
  145. }
  146. std::string event = announceList.getEventString();
  147. if(!event.empty()) {
  148. url += std::string("&")+"event="+event;
  149. }
  150. if(!trackerId.empty()) {
  151. url += std::string("&")+"trackerid="+Util::torrentUrlencode((const unsigned char*)trackerId.c_str(),
  152. trackerId.size());
  153. }
  154. return url;
  155. }
  156. void DefaultBtAnnounce::announceStart() {
  157. trackers++;
  158. }
  159. void DefaultBtAnnounce::announceSuccess() {
  160. trackers = 0;
  161. announceList.announceSuccess();
  162. }
  163. void DefaultBtAnnounce::announceFailure() {
  164. trackers = 0;
  165. announceList.announceFailure();
  166. }
  167. bool DefaultBtAnnounce::isAllAnnounceFailed() {
  168. return announceList.allTiersFailed();
  169. }
  170. void DefaultBtAnnounce::resetAnnounce() {
  171. prevAnnounceTime.reset();
  172. announceList.resetTier();
  173. }
  174. void
  175. DefaultBtAnnounce::processAnnounceResponse(const char* trackerResponse,
  176. size_t trackerResponseLength)
  177. {
  178. SharedHandle<MetaEntry> entry(MetaFileUtil::bdecoding(trackerResponse,
  179. trackerResponseLength));
  180. const Dictionary* response = dynamic_cast<const Dictionary*>(entry.get());
  181. if(!response) {
  182. throw new DlAbortEx(MSG_NULL_TRACKER_RESPONSE);
  183. }
  184. const Data* failureReasonData = dynamic_cast<const Data*>(response->get("failure reason"));
  185. if(failureReasonData) {
  186. throw new DlAbortEx(EX_TRACKER_FAILURE,
  187. failureReasonData->toString().c_str());
  188. }
  189. const Data* warningMessageData = dynamic_cast<const Data*>(response->get("warning message"));
  190. if(warningMessageData) {
  191. logger->warn(MSG_TRACKER_WARNING_MESSAGE,
  192. warningMessageData->toString().c_str());
  193. }
  194. const Data* trackerIdData = dynamic_cast<const Data*>(response->get("tracker id"));
  195. if(trackerIdData) {
  196. trackerId = trackerIdData->toString();
  197. logger->debug("Tracker ID:%s", trackerId.c_str());
  198. }
  199. const Data* intervalData = dynamic_cast<const Data*>(response->get("interval"));
  200. if(intervalData) {
  201. int32_t t = intervalData->toInt();
  202. if(t > 0) {
  203. interval = intervalData->toInt();
  204. logger->debug("Interval:%d", interval);
  205. }
  206. }
  207. const Data* minIntervalData = dynamic_cast<const Data*>(response->get("min interval"));
  208. if(minIntervalData) {
  209. int32_t t = minIntervalData->toInt();
  210. if(t > 0) {
  211. minInterval = minIntervalData->toInt();
  212. logger->debug("Min interval:%d", minInterval);
  213. }
  214. }
  215. if(minInterval > interval) {
  216. minInterval = interval;
  217. }
  218. const Data* completeData = dynamic_cast<const Data*>(response->get("complete"));
  219. if(completeData) {
  220. complete = completeData->toInt();
  221. logger->debug("Complete:%d", complete);
  222. }
  223. const Data* incompleteData = dynamic_cast<const Data*>(response->get("incomplete"));
  224. if(incompleteData) {
  225. incomplete = incompleteData->toInt();
  226. logger->debug("Incomplete:%d", incomplete);
  227. }
  228. const MetaEntry* peersEntry = response->get("peers");
  229. if(peersEntry &&
  230. !btRuntime->isHalt() &&
  231. btRuntime->lessThanMinPeer()) {
  232. DelegatingPeerListProcessor proc(btContext->getPieceLength(),
  233. btContext->getTotalLength());
  234. Peers peers = proc.extractPeer(peersEntry);
  235. peerStorage->addPeer(peers);
  236. }
  237. if(!peersEntry) {
  238. logger->info(MSG_NO_PEER_LIST_RECEIVED);
  239. }
  240. }
  241. bool DefaultBtAnnounce::noMoreAnnounce() {
  242. return (trackers == 0 &&
  243. btRuntime->isHalt() &&
  244. !announceList.countStoppedAllowedTier());
  245. }
  246. void DefaultBtAnnounce::shuffleAnnounce() {
  247. announceList.shuffle();
  248. }
  249. void DefaultBtAnnounce::setRandomizer(const RandomizerHandle& randomizer)
  250. {
  251. _randomizer = randomizer;
  252. }
  253. void DefaultBtAnnounce::setBtRuntime(const BtRuntimeHandle& btRuntime)
  254. {
  255. this->btRuntime = btRuntime;
  256. }
  257. BtRuntimeHandle DefaultBtAnnounce::getBtRuntime() const
  258. {
  259. return btRuntime;
  260. }
  261. void DefaultBtAnnounce::setPieceStorage(const PieceStorageHandle& pieceStorage)
  262. {
  263. this->pieceStorage = pieceStorage;
  264. }
  265. PieceStorageHandle DefaultBtAnnounce::getPieceStorage() const
  266. {
  267. return pieceStorage;
  268. }
  269. void DefaultBtAnnounce::setPeerStorage(const PeerStorageHandle& peerStorage)
  270. {
  271. this->peerStorage = peerStorage;
  272. }
  273. PeerStorageHandle DefaultBtAnnounce::getPeerStorage() const
  274. {
  275. return peerStorage;
  276. }
  277. } // namespace aria2