DefaultBtAnnounce.cc 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  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 "MetaFileUtil.h"
  39. #include "Dictionary.h"
  40. #include "List.h"
  41. #include "Data.h"
  42. #include "DelegatingPeerListProcessor.h"
  43. #include "Util.h"
  44. #include "prefs.h"
  45. #include "DlAbortEx.h"
  46. #include "message.h"
  47. #include "SimpleRandomizer.h"
  48. DefaultBtAnnounce::DefaultBtAnnounce(BtContextHandle btContext,
  49. const Option* option):
  50. btContext(btContext),
  51. trackers(0),
  52. interval(DEFAULT_ANNOUNCE_INTERVAL),
  53. minInterval(DEFAULT_ANNOUNCE_INTERVAL),
  54. complete(0),
  55. incomplete(0),
  56. announceList(btContext->getAnnounceTiers()),
  57. option(option),
  58. logger(LogFactory::getInstance()),
  59. _randomizer(SimpleRandomizer::getInstance()),
  60. btRuntime(BT_RUNTIME(btContext)),
  61. pieceStorage(PIECE_STORAGE(btContext)),
  62. peerStorage(PEER_STORAGE(btContext))
  63. {
  64. prevAnnounceTime.setTimeInSec(0);
  65. generateKey();
  66. }
  67. DefaultBtAnnounce::~DefaultBtAnnounce() {
  68. }
  69. void DefaultBtAnnounce::generateKey()
  70. {
  71. key = Util::randomAlpha(8, _randomizer);
  72. }
  73. bool DefaultBtAnnounce::isDefaultAnnounceReady() {
  74. return (trackers == 0 && prevAnnounceTime.elapsed(minInterval) &&
  75. !announceList.allTiersFailed());
  76. }
  77. bool DefaultBtAnnounce::isStoppedAnnounceReady() {
  78. return (trackers == 0 &&
  79. btRuntime->isHalt() &&
  80. announceList.countStoppedAllowedTier());
  81. }
  82. bool DefaultBtAnnounce::isCompletedAnnounceReady() {
  83. return (trackers == 0 &&
  84. pieceStorage->allDownloadFinished() &&
  85. announceList.countCompletedAllowedTier());
  86. }
  87. bool DefaultBtAnnounce::isAnnounceReady() {
  88. return
  89. isStoppedAnnounceReady() ||
  90. isCompletedAnnounceReady() ||
  91. isDefaultAnnounceReady();
  92. }
  93. string DefaultBtAnnounce::getAnnounceUrl() {
  94. if(isStoppedAnnounceReady()) {
  95. if(!announceList.currentTierAcceptsStoppedEvent()) {
  96. announceList.moveToStoppedAllowedTier();
  97. }
  98. announceList.setEvent(AnnounceTier::STOPPED);
  99. } else if(isCompletedAnnounceReady()) {
  100. if(!announceList.currentTierAcceptsCompletedEvent()) {
  101. announceList.moveToCompletedAllowedTier();
  102. }
  103. announceList.setEvent(AnnounceTier::COMPLETED);
  104. } else if(isDefaultAnnounceReady()) {
  105. // If download completed before "started" event is sent to a tracker,
  106. // we change the event to something else to prevent us from
  107. // sending "completed" event.
  108. if(pieceStorage->allDownloadFinished() &&
  109. announceList.getEvent() == AnnounceTier::STARTED) {
  110. announceList.setEvent(AnnounceTier::STARTED_AFTER_COMPLETION);
  111. }
  112. } else {
  113. return "";
  114. }
  115. int32_t numWant = 50;
  116. if(!btRuntime->lessThanEqMinPeer() ||
  117. btRuntime->isHalt()) {
  118. numWant = 0;
  119. }
  120. TransferStat stat = peerStorage->calculateStat();
  121. int64_t left = pieceStorage->getTotalLength()-pieceStorage->getCompletedLength();
  122. if(left < 0) {
  123. left = 0;
  124. }
  125. string url = announceList.getAnnounce()+"?"+
  126. "info_hash="+Util::torrentUrlencode(btContext->getInfoHash(),
  127. btContext->getInfoHashLength())+"&"+
  128. "peer_id="+Util::torrentUrlencode(btContext->getPeerId(), 20)+"&"+
  129. "uploaded="+Util::llitos(stat.getSessionUploadLength())+"&"+
  130. "downloaded="+Util::llitos(stat.getSessionDownloadLength())+"&"+
  131. "left="+Util::llitos(left)+"&"+
  132. "compact=1"+"&"+
  133. "key="+key+"&"+
  134. "numwant="+Util::itos(numWant)+"&"+
  135. "no_peer_id=1";
  136. if(btRuntime->getListenPort() > 0) {
  137. url += string("&")+"port="+Util::itos(btRuntime->getListenPort());
  138. }
  139. string event = announceList.getEventString();
  140. if(!event.empty()) {
  141. url += string("&")+"event="+event;
  142. }
  143. if(!trackerId.empty()) {
  144. url += string("&")+"trackerid="+Util::torrentUrlencode((const unsigned char*)trackerId.c_str(),
  145. trackerId.size());
  146. }
  147. return url;
  148. }
  149. void DefaultBtAnnounce::announceStart() {
  150. trackers++;
  151. }
  152. void DefaultBtAnnounce::announceSuccess() {
  153. trackers = 0;
  154. announceList.announceSuccess();
  155. }
  156. void DefaultBtAnnounce::announceFailure() {
  157. trackers = 0;
  158. announceList.announceFailure();
  159. }
  160. bool DefaultBtAnnounce::isAllAnnounceFailed() {
  161. return announceList.allTiersFailed();
  162. }
  163. void DefaultBtAnnounce::resetAnnounce() {
  164. prevAnnounceTime.reset();
  165. announceList.resetTier();
  166. }
  167. void
  168. DefaultBtAnnounce::processAnnounceResponse(const char* trackerResponse,
  169. size_t trackerResponseLength)
  170. {
  171. SharedHandle<MetaEntry> entry(MetaFileUtil::bdecoding(trackerResponse,
  172. trackerResponseLength));
  173. Dictionary* response = (Dictionary*)entry.get();
  174. Data* failureReasonData = (Data*)response->get("failure reason");
  175. if(failureReasonData) {
  176. throw new DlAbortEx(EX_TRACKER_FAILURE,
  177. failureReasonData->toString().c_str());
  178. }
  179. Data* warningMessageData = (Data*)response->get("warning message");
  180. if(warningMessageData) {
  181. logger->warn(MSG_TRACKER_WARNING_MESSAGE,
  182. warningMessageData->toString().c_str());
  183. }
  184. Data* trackerIdData = (Data*)response->get("tracker id");
  185. if(trackerIdData) {
  186. trackerId = trackerIdData->toString();
  187. logger->debug("Tracker ID:%s", trackerId.c_str());
  188. }
  189. Data* intervalData = (Data*)response->get("interval");
  190. if(intervalData) {
  191. interval = intervalData->toInt();
  192. logger->debug("Interval:%d", interval);
  193. }
  194. Data* minIntervalData = (Data*)response->get("min interval");
  195. if(minIntervalData) {
  196. minInterval = minIntervalData->toInt();
  197. logger->debug("Min interval:%d", minInterval);
  198. }
  199. if(minInterval > interval) {
  200. minInterval = interval;
  201. }
  202. Data* completeData = (Data*)response->get("complete");
  203. if(completeData) {
  204. complete = completeData->toInt();
  205. logger->debug("Complete:%d", complete);
  206. }
  207. Data* incompleteData = (Data*)response->get("incomplete");
  208. if(incompleteData) {
  209. incomplete = incompleteData->toInt();
  210. logger->debug("Incomplete:%d", incomplete);
  211. }
  212. const MetaEntry* peersEntry = response->get("peers");
  213. if(peersEntry &&
  214. !btRuntime->isHalt() &&
  215. btRuntime->lessThanMinPeer()) {
  216. DelegatingPeerListProcessor proc(btContext->getPieceLength(),
  217. btContext->getTotalLength());
  218. Peers peers = proc.extractPeer(peersEntry);
  219. peerStorage->addPeer(peers);
  220. }
  221. if(!peersEntry) {
  222. logger->info(MSG_NO_PEER_LIST_RECEIVED);
  223. }
  224. }
  225. bool DefaultBtAnnounce::noMoreAnnounce() {
  226. return (trackers == 0 &&
  227. btRuntime->isHalt() &&
  228. !announceList.countStoppedAllowedTier());
  229. }
  230. void DefaultBtAnnounce::shuffleAnnounce() {
  231. announceList.shuffle();
  232. }
  233. void DefaultBtAnnounce::setRandomizer(const RandomizerHandle& randomizer)
  234. {
  235. _randomizer = randomizer;
  236. }