DefaultBtAnnounce.cc 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  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 "util.h"
  39. #include "prefs.h"
  40. #include "DlAbortEx.h"
  41. #include "message.h"
  42. #include "SimpleRandomizer.h"
  43. #include "DownloadContext.h"
  44. #include "PieceStorage.h"
  45. #include "BtRuntime.h"
  46. #include "PeerStorage.h"
  47. #include "Peer.h"
  48. #include "Option.h"
  49. #include "fmt.h"
  50. #include "A2STR.h"
  51. #include "bencode2.h"
  52. #include "bittorrent_helper.h"
  53. #include "wallclock.h"
  54. #include "uri.h"
  55. #include "UDPTrackerRequest.h"
  56. #include "SocketCore.h"
  57. namespace aria2 {
  58. DefaultBtAnnounce::DefaultBtAnnounce
  59. (DownloadContext* downloadContext, const Option* option)
  60. : downloadContext_{downloadContext},
  61. trackers_(0),
  62. prevAnnounceTimer_(Timer::zero()),
  63. interval_(DEFAULT_ANNOUNCE_INTERVAL),
  64. minInterval_(DEFAULT_ANNOUNCE_INTERVAL),
  65. userDefinedInterval_(0_s),
  66. complete_(0),
  67. incomplete_(0),
  68. announceList_(bittorrent::getTorrentAttrs(downloadContext)->announceList),
  69. option_(option),
  70. randomizer_(SimpleRandomizer::getInstance().get()),
  71. tcpPort_(0)
  72. {}
  73. DefaultBtAnnounce::~DefaultBtAnnounce() {
  74. }
  75. bool DefaultBtAnnounce::isDefaultAnnounceReady() {
  76. return (trackers_ == 0 &&
  77. prevAnnounceTimer_.difference(global::wallclock()) >=
  78. (userDefinedInterval_.count() == 0 ? minInterval_
  79. : userDefinedInterval_) &&
  80. !announceList_.allTiersFailed());
  81. }
  82. bool DefaultBtAnnounce::isStoppedAnnounceReady() {
  83. return (trackers_ == 0 &&
  84. btRuntime_->isHalt() &&
  85. announceList_.countStoppedAllowedTier());
  86. }
  87. bool DefaultBtAnnounce::isCompletedAnnounceReady() {
  88. return (trackers_ == 0 &&
  89. pieceStorage_->allDownloadFinished() &&
  90. announceList_.countCompletedAllowedTier());
  91. }
  92. bool DefaultBtAnnounce::isAnnounceReady() {
  93. return
  94. isStoppedAnnounceReady() ||
  95. isCompletedAnnounceReady() ||
  96. isDefaultAnnounceReady();
  97. }
  98. namespace {
  99. bool uriHasQuery(const std::string& uri)
  100. {
  101. uri_split_result us;
  102. if(uri_split(&us, uri.c_str()) == 0) {
  103. return (us.field_set & (1 << USR_QUERY)) && us.fields[USR_QUERY].len > 0;
  104. } else {
  105. return false;
  106. }
  107. }
  108. } // namespace
  109. bool DefaultBtAnnounce::adjustAnnounceList() {
  110. if(isStoppedAnnounceReady()) {
  111. if(!announceList_.currentTierAcceptsStoppedEvent()) {
  112. announceList_.moveToStoppedAllowedTier();
  113. }
  114. announceList_.setEvent(AnnounceTier::STOPPED);
  115. } else if(isCompletedAnnounceReady()) {
  116. if(!announceList_.currentTierAcceptsCompletedEvent()) {
  117. announceList_.moveToCompletedAllowedTier();
  118. }
  119. announceList_.setEvent(AnnounceTier::COMPLETED);
  120. } else if(isDefaultAnnounceReady()) {
  121. // If download completed before "started" event is sent to a tracker,
  122. // we change the event to something else to prevent us from
  123. // sending "completed" event.
  124. if(pieceStorage_->allDownloadFinished() &&
  125. announceList_.getEvent() == AnnounceTier::STARTED) {
  126. announceList_.setEvent(AnnounceTier::STARTED_AFTER_COMPLETION);
  127. }
  128. } else {
  129. return false;
  130. }
  131. return true;
  132. }
  133. std::string DefaultBtAnnounce::getAnnounceUrl() {
  134. if(!adjustAnnounceList()) {
  135. return A2STR::NIL;
  136. }
  137. int numWant = 50;
  138. if(!btRuntime_->lessThanMinPeers() || btRuntime_->isHalt()) {
  139. numWant = 0;
  140. }
  141. NetStat& stat = downloadContext_->getNetStat();
  142. int64_t left =
  143. pieceStorage_->getTotalLength()-pieceStorage_->getCompletedLength();
  144. // Use last 8 bytes of peer ID as a key
  145. const size_t keyLen = 8;
  146. std::string uri = announceList_.getAnnounce();
  147. uri += uriHasQuery(uri) ? "&" : "?";
  148. uri += fmt("info_hash=%s&"
  149. "peer_id=%s&"
  150. "uploaded=%" PRId64 "&"
  151. "downloaded=%" PRId64 "&"
  152. "left=%" PRId64 "&"
  153. "compact=1&"
  154. "key=%s&"
  155. "numwant=%d&"
  156. "no_peer_id=1",
  157. util::torrentPercentEncode
  158. (bittorrent::getInfoHash(downloadContext_),
  159. INFO_HASH_LENGTH).c_str(),
  160. util::torrentPercentEncode
  161. (bittorrent::getStaticPeerId(), PEER_ID_LENGTH).c_str(),
  162. stat.getSessionUploadLength(),
  163. stat.getSessionDownloadLength(),
  164. left,
  165. util::torrentPercentEncode
  166. (bittorrent::getStaticPeerId()+PEER_ID_LENGTH-keyLen,
  167. keyLen).c_str(),
  168. numWant);
  169. if(tcpPort_) {
  170. uri += fmt("&port=%u", tcpPort_);
  171. }
  172. const char* event = announceList_.getEventString();
  173. if(event[0]) {
  174. uri += "&event=";
  175. uri += event;
  176. }
  177. if(!trackerId_.empty()) {
  178. uri += "&trackerid=";
  179. uri += util::torrentPercentEncode(trackerId_);
  180. }
  181. if(option_->getAsBool(PREF_BT_FORCE_ENCRYPTION) ||
  182. option_->getAsBool(PREF_BT_REQUIRE_CRYPTO)) {
  183. uri += "&requirecrypto=1";
  184. } else {
  185. uri += "&supportcrypto=1";
  186. }
  187. if(!option_->blank(PREF_BT_EXTERNAL_IP)) {
  188. uri += "&ip=";
  189. uri += option_->get(PREF_BT_EXTERNAL_IP);
  190. }
  191. return uri;
  192. }
  193. std::shared_ptr<UDPTrackerRequest> DefaultBtAnnounce::createUDPTrackerRequest
  194. (const std::string& remoteAddr, uint16_t remotePort, uint16_t localPort)
  195. {
  196. if(!adjustAnnounceList()) {
  197. return nullptr;
  198. }
  199. NetStat& stat = downloadContext_->getNetStat();
  200. int64_t left =
  201. pieceStorage_->getTotalLength()-pieceStorage_->getCompletedLength();
  202. auto req = std::make_shared<UDPTrackerRequest>();
  203. req->remoteAddr = remoteAddr;
  204. req->remotePort = remotePort;
  205. req->action = UDPT_ACT_ANNOUNCE;
  206. req->infohash = bittorrent::getTorrentAttrs(downloadContext_)->infoHash;
  207. const unsigned char* peerId = bittorrent::getStaticPeerId();
  208. req->peerId.assign(peerId, peerId + PEER_ID_LENGTH);
  209. req->downloaded = stat.getSessionDownloadLength();
  210. req->left = left;
  211. req->uploaded = stat.getSessionUploadLength();
  212. switch(announceList_.getEvent()) {
  213. case AnnounceTier::STARTED:
  214. case AnnounceTier::STARTED_AFTER_COMPLETION:
  215. req->event = UDPT_EVT_STARTED;
  216. break;
  217. case AnnounceTier::STOPPED:
  218. req->event = UDPT_EVT_STOPPED;
  219. break;
  220. case AnnounceTier::COMPLETED:
  221. req->event = UDPT_EVT_COMPLETED;
  222. break;
  223. default:
  224. req->event = 0;
  225. }
  226. if(!option_->blank(PREF_BT_EXTERNAL_IP)) {
  227. unsigned char dest[16];
  228. if(net::getBinAddr(dest, option_->get(PREF_BT_EXTERNAL_IP)) == 4) {
  229. memcpy(&req->ip, dest, 4);
  230. } else {
  231. req->ip = 0;
  232. }
  233. } else {
  234. req->ip = 0;
  235. }
  236. req->key = randomizer_->getRandomNumber(INT32_MAX);
  237. int numWant = 50;
  238. if(!btRuntime_->lessThanMinPeers() || btRuntime_->isHalt()) {
  239. numWant = 0;
  240. }
  241. req->numWant = numWant;
  242. req->port = localPort;
  243. req->extensions = 0;
  244. return req;
  245. }
  246. void DefaultBtAnnounce::announceStart() {
  247. ++trackers_;
  248. }
  249. void DefaultBtAnnounce::announceSuccess() {
  250. trackers_ = 0;
  251. announceList_.announceSuccess();
  252. }
  253. void DefaultBtAnnounce::announceFailure() {
  254. trackers_ = 0;
  255. announceList_.announceFailure();
  256. }
  257. bool DefaultBtAnnounce::isAllAnnounceFailed() {
  258. return announceList_.allTiersFailed();
  259. }
  260. void DefaultBtAnnounce::resetAnnounce() {
  261. prevAnnounceTimer_ = global::wallclock();
  262. announceList_.resetTier();
  263. }
  264. void
  265. DefaultBtAnnounce::processAnnounceResponse(const unsigned char* trackerResponse,
  266. size_t trackerResponseLength)
  267. {
  268. A2_LOG_DEBUG("Now processing tracker response.");
  269. auto decodedValue = bencode2::decode(trackerResponse, trackerResponseLength);
  270. const Dict* dict = downcast<Dict>(decodedValue);
  271. if(!dict) {
  272. throw DL_ABORT_EX(MSG_NULL_TRACKER_RESPONSE);
  273. }
  274. const String* failure = downcast<String>(dict->get(BtAnnounce::FAILURE_REASON));
  275. if(failure) {
  276. throw DL_ABORT_EX
  277. (fmt(EX_TRACKER_FAILURE, failure->s().c_str()));
  278. }
  279. const String* warn = downcast<String>(dict->get(BtAnnounce::WARNING_MESSAGE));
  280. if(warn) {
  281. A2_LOG_WARN(fmt(MSG_TRACKER_WARNING_MESSAGE, warn->s().c_str()));
  282. }
  283. const String* tid = downcast<String>(dict->get(BtAnnounce::TRACKER_ID));
  284. if(tid) {
  285. trackerId_ = tid->s();
  286. A2_LOG_DEBUG(fmt("Tracker ID:%s", trackerId_.c_str()));
  287. }
  288. const Integer* ival = downcast<Integer>(dict->get(BtAnnounce::INTERVAL));
  289. if(ival && ival->i() > 0) {
  290. interval_ = std::chrono::seconds(ival->i());
  291. A2_LOG_DEBUG(fmt("Interval:%ld", static_cast<long int>(interval_.count())));
  292. }
  293. const Integer* mival = downcast<Integer>(dict->get(BtAnnounce::MIN_INTERVAL));
  294. if(mival && mival->i() > 0) {
  295. minInterval_ = std::chrono::seconds(mival->i());
  296. A2_LOG_DEBUG(
  297. fmt("Min interval:%ld", static_cast<long int>(minInterval_.count())));
  298. minInterval_ = std::min(minInterval_, interval_);
  299. } else {
  300. // Use interval as a minInterval if minInterval is not supplied.
  301. minInterval_ = interval_;
  302. }
  303. const Integer* comp = downcast<Integer>(dict->get(BtAnnounce::COMPLETE));
  304. if(comp && comp->i() >= 0) {
  305. complete_ = comp->i();
  306. A2_LOG_DEBUG(fmt("Complete:%d", complete_));
  307. }
  308. const Integer* incomp = downcast<Integer>(dict->get(BtAnnounce::INCOMPLETE));
  309. if(incomp && incomp->i() >= 0) {
  310. incomplete_ = incomp->i();
  311. A2_LOG_DEBUG(fmt("Incomplete:%d", incomplete_));
  312. }
  313. auto peerData = dict->get(BtAnnounce::PEERS);
  314. if(!peerData) {
  315. A2_LOG_INFO(MSG_NO_PEER_LIST_RECEIVED);
  316. } else {
  317. if(!btRuntime_->isHalt() && btRuntime_->lessThanMinPeers()) {
  318. std::vector<std::shared_ptr<Peer> > peers;
  319. bittorrent::extractPeer(peerData, AF_INET, std::back_inserter(peers));
  320. peerStorage_->addPeer(peers);
  321. }
  322. }
  323. auto peer6Data = dict->get(BtAnnounce::PEERS6);
  324. if(!peer6Data) {
  325. A2_LOG_INFO("No peers6 received.");
  326. } else {
  327. if(!btRuntime_->isHalt() && btRuntime_->lessThanMinPeers()) {
  328. std::vector<std::shared_ptr<Peer> > peers;
  329. bittorrent::extractPeer(peer6Data, AF_INET6, std::back_inserter(peers));
  330. peerStorage_->addPeer(peers);
  331. }
  332. }
  333. }
  334. void DefaultBtAnnounce::processUDPTrackerResponse
  335. (const std::shared_ptr<UDPTrackerRequest>& req)
  336. {
  337. const std::shared_ptr<UDPTrackerReply>& reply = req->reply;
  338. A2_LOG_DEBUG("Now processing UDP tracker response.");
  339. if(reply->interval > 0) {
  340. minInterval_ = std::chrono::seconds(reply->interval);
  341. A2_LOG_DEBUG(
  342. fmt("Min interval:%ld", static_cast<long int>(minInterval_.count())));
  343. interval_ = minInterval_;
  344. }
  345. complete_ = reply->seeders;
  346. A2_LOG_DEBUG(fmt("Complete:%d", reply->seeders));
  347. incomplete_ = reply->leechers;
  348. A2_LOG_DEBUG(fmt("Incomplete:%d", reply->leechers));
  349. if(!btRuntime_->isHalt() && btRuntime_->lessThanMinPeers()) {
  350. for(auto & elem : reply->peers) {
  351. peerStorage_->addPeer(std::make_shared<Peer>(elem.first, elem.second));
  352. }
  353. }
  354. }
  355. bool DefaultBtAnnounce::noMoreAnnounce() {
  356. return (trackers_ == 0 &&
  357. btRuntime_->isHalt() &&
  358. !announceList_.countStoppedAllowedTier());
  359. }
  360. void DefaultBtAnnounce::shuffleAnnounce() {
  361. announceList_.shuffle();
  362. }
  363. void DefaultBtAnnounce::setRandomizer(Randomizer* randomizer)
  364. {
  365. randomizer_ = randomizer;
  366. }
  367. void DefaultBtAnnounce::setBtRuntime(const std::shared_ptr<BtRuntime>& btRuntime)
  368. {
  369. btRuntime_ = btRuntime;
  370. }
  371. void DefaultBtAnnounce::setPieceStorage(const std::shared_ptr<PieceStorage>& pieceStorage)
  372. {
  373. pieceStorage_ = pieceStorage;
  374. }
  375. void DefaultBtAnnounce::setPeerStorage
  376. (const std::shared_ptr<PeerStorage>& peerStorage)
  377. {
  378. peerStorage_ = peerStorage;
  379. }
  380. void DefaultBtAnnounce::overrideMinInterval(std::chrono::seconds interval)
  381. {
  382. minInterval_ = std::move(interval);
  383. }
  384. } // namespace aria2