DefaultBtAnnounce.cc 13 KB

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