TrackerWatcherCommand.cc 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  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 "TrackerWatcherCommand.h"
  36. #include <sstream>
  37. #include "DownloadEngine.h"
  38. #include "BtAnnounce.h"
  39. #include "BtRuntime.h"
  40. #include "PieceStorage.h"
  41. #include "PeerStorage.h"
  42. #include "Peer.h"
  43. #include "prefs.h"
  44. #include "message.h"
  45. #include "ByteArrayDiskWriterFactory.h"
  46. #include "RecoverableException.h"
  47. #include "PeerInitiateConnectionCommand.h"
  48. #include "DiskAdaptor.h"
  49. #include "FileEntry.h"
  50. #include "RequestGroup.h"
  51. #include "Option.h"
  52. #include "DlAbortEx.h"
  53. #include "Logger.h"
  54. #include "LogFactory.h"
  55. #include "A2STR.h"
  56. #include "SocketCore.h"
  57. #include "Request.h"
  58. #include "AnnounceTier.h"
  59. #include "DownloadContext.h"
  60. #include "bittorrent_helper.h"
  61. #include "a2functional.h"
  62. #include "util.h"
  63. #include "fmt.h"
  64. #include "UDPTrackerRequest.h"
  65. #include "UDPTrackerClient.h"
  66. #include "BtRegistry.h"
  67. #include "NameResolveCommand.h"
  68. namespace aria2 {
  69. HTTPAnnRequest::HTTPAnnRequest(std::unique_ptr<RequestGroup> rg)
  70. : rg_{std::move(rg)}
  71. {
  72. }
  73. HTTPAnnRequest::~HTTPAnnRequest() {}
  74. bool HTTPAnnRequest::stopped() const { return rg_->getNumCommand() == 0; }
  75. bool HTTPAnnRequest::success() const { return rg_->downloadFinished(); }
  76. void HTTPAnnRequest::stop(DownloadEngine* e)
  77. {
  78. rg_->setForceHaltRequested(true);
  79. }
  80. bool HTTPAnnRequest::issue(DownloadEngine* e)
  81. {
  82. try {
  83. std::vector<std::unique_ptr<Command>> commands;
  84. rg_->createInitialCommand(commands, e);
  85. e->addCommand(std::move(commands));
  86. e->setNoWait(true);
  87. A2_LOG_DEBUG("added tracker request command");
  88. return true;
  89. }
  90. catch (RecoverableException& ex) {
  91. A2_LOG_ERROR_EX(EX_EXCEPTION_CAUGHT, ex);
  92. return false;
  93. }
  94. }
  95. bool HTTPAnnRequest::processResponse(
  96. const std::shared_ptr<BtAnnounce>& btAnnounce)
  97. {
  98. try {
  99. std::stringstream strm;
  100. unsigned char data[2048];
  101. rg_->getPieceStorage()->getDiskAdaptor()->openFile();
  102. while (1) {
  103. ssize_t dataLength = rg_->getPieceStorage()->getDiskAdaptor()->readData(
  104. data, sizeof(data), strm.tellp());
  105. if (dataLength == 0) {
  106. break;
  107. }
  108. strm.write(reinterpret_cast<const char*>(data), dataLength);
  109. }
  110. std::string res = strm.str();
  111. btAnnounce->processAnnounceResponse(
  112. reinterpret_cast<const unsigned char*>(res.c_str()), res.size());
  113. return true;
  114. }
  115. catch (RecoverableException& e) {
  116. const auto& dctx = rg_->getDownloadContext();
  117. const auto& fe = dctx->getFirstFileEntry();
  118. auto uris = fe->getUris();
  119. A2_LOG_ERROR_EX(fmt("GID#%s - Tracker request %s failed",
  120. GroupId::toHex(rg_->getGID()).c_str(), uris[0].c_str()),
  121. e);
  122. return false;
  123. }
  124. }
  125. UDPAnnRequest::UDPAnnRequest(const std::shared_ptr<UDPTrackerRequest>& req)
  126. : req_(req)
  127. {
  128. }
  129. UDPAnnRequest::~UDPAnnRequest() {}
  130. bool UDPAnnRequest::stopped() const
  131. {
  132. return !req_ || req_->state == UDPT_STA_COMPLETE;
  133. }
  134. bool UDPAnnRequest::success() const
  135. {
  136. return req_ && req_->state == UDPT_STA_COMPLETE &&
  137. req_->error == UDPT_ERR_SUCCESS;
  138. }
  139. void UDPAnnRequest::stop(DownloadEngine* e)
  140. {
  141. if (req_) {
  142. req_.reset();
  143. }
  144. }
  145. bool UDPAnnRequest::issue(DownloadEngine* e)
  146. {
  147. if (req_) {
  148. e->addCommand(make_unique<NameResolveCommand>(e->newCUID(), e, req_));
  149. e->setNoWait(true);
  150. return true;
  151. }
  152. else {
  153. return false;
  154. }
  155. }
  156. bool UDPAnnRequest::processResponse(
  157. const std::shared_ptr<BtAnnounce>& btAnnounce)
  158. {
  159. if (req_) {
  160. btAnnounce->processUDPTrackerResponse(req_);
  161. return true;
  162. }
  163. else {
  164. return false;
  165. }
  166. }
  167. TrackerWatcherCommand::TrackerWatcherCommand(cuid_t cuid,
  168. RequestGroup* requestGroup,
  169. DownloadEngine* e)
  170. : Command(cuid),
  171. requestGroup_(requestGroup),
  172. e_(e),
  173. udpTrackerClient_(e_->getBtRegistry()->getUDPTrackerClient())
  174. {
  175. requestGroup_->increaseNumCommand();
  176. if (udpTrackerClient_) {
  177. udpTrackerClient_->increaseWatchers();
  178. }
  179. }
  180. TrackerWatcherCommand::~TrackerWatcherCommand()
  181. {
  182. requestGroup_->decreaseNumCommand();
  183. if (udpTrackerClient_) {
  184. udpTrackerClient_->decreaseWatchers();
  185. }
  186. }
  187. bool TrackerWatcherCommand::execute()
  188. {
  189. if (requestGroup_->isForceHaltRequested()) {
  190. if (!trackerRequest_) {
  191. return true;
  192. }
  193. else if (trackerRequest_->stopped() || trackerRequest_->success()) {
  194. return true;
  195. }
  196. else {
  197. trackerRequest_->stop(e_);
  198. e_->setRefreshInterval(std::chrono::milliseconds(0));
  199. e_->addCommand(std::unique_ptr<Command>(this));
  200. return false;
  201. }
  202. }
  203. if (btAnnounce_->noMoreAnnounce()) {
  204. A2_LOG_DEBUG("no more announce");
  205. return true;
  206. }
  207. if (!trackerRequest_) {
  208. trackerRequest_ = createAnnounce(e_);
  209. if (trackerRequest_) {
  210. trackerRequest_->issue(e_);
  211. A2_LOG_DEBUG("tracker request created");
  212. }
  213. }
  214. else if (trackerRequest_->stopped()) {
  215. // We really want to make sure that tracker request has finished
  216. // by checking getNumCommand() == 0. Because we reset
  217. // trackerRequestGroup_, if it is still used in other Command, we
  218. // will get Segmentation fault.
  219. if (trackerRequest_->success()) {
  220. if (trackerRequest_->processResponse(btAnnounce_)) {
  221. btAnnounce_->announceSuccess();
  222. btAnnounce_->resetAnnounce();
  223. addConnection();
  224. }
  225. else {
  226. btAnnounce_->announceFailure();
  227. if (btAnnounce_->isAllAnnounceFailed()) {
  228. btAnnounce_->resetAnnounce();
  229. }
  230. }
  231. trackerRequest_.reset();
  232. }
  233. else {
  234. // handle errors here
  235. btAnnounce_->announceFailure(); // inside it, trackers = 0.
  236. trackerRequest_.reset();
  237. if (btAnnounce_->isAllAnnounceFailed()) {
  238. btAnnounce_->resetAnnounce();
  239. }
  240. }
  241. }
  242. if (!trackerRequest_ && btAnnounce_->noMoreAnnounce()) {
  243. A2_LOG_DEBUG("no more announce");
  244. return true;
  245. }
  246. e_->addCommand(std::unique_ptr<Command>(this));
  247. return false;
  248. }
  249. void TrackerWatcherCommand::addConnection()
  250. {
  251. while (!btRuntime_->isHalt() && btRuntime_->lessThanMinPeers()) {
  252. if (!peerStorage_->isPeerAvailable()) {
  253. break;
  254. }
  255. cuid_t ncuid = e_->newCUID();
  256. std::shared_ptr<Peer> peer = peerStorage_->checkoutPeer(ncuid);
  257. // sanity check
  258. if (!peer) {
  259. break;
  260. }
  261. auto command = make_unique<PeerInitiateConnectionCommand>(
  262. ncuid, requestGroup_, peer, e_, btRuntime_);
  263. command->setPeerStorage(peerStorage_);
  264. command->setPieceStorage(pieceStorage_);
  265. e_->addCommand(std::move(command));
  266. A2_LOG_DEBUG(fmt("CUID#%" PRId64 " - Adding new command CUID#%" PRId64 "",
  267. getCuid(), peer->usedBy()));
  268. }
  269. }
  270. std::unique_ptr<AnnRequest>
  271. TrackerWatcherCommand::createAnnounce(DownloadEngine* e)
  272. {
  273. while (!btAnnounce_->isAllAnnounceFailed() &&
  274. btAnnounce_->isAnnounceReady()) {
  275. std::string uri = btAnnounce_->getAnnounceUrl();
  276. uri_split_result res;
  277. memset(&res, 0, sizeof(res));
  278. if (uri_split(&res, uri.c_str()) == 0) {
  279. // Without UDP tracker support, send it to normal tracker flow
  280. // and make it fail.
  281. std::unique_ptr<AnnRequest> treq;
  282. if (udpTrackerClient_ &&
  283. uri::getFieldString(res, USR_SCHEME, uri.c_str()) == "udp") {
  284. uint16_t localPort;
  285. localPort = e->getBtRegistry()->getTcpPort();
  286. treq =
  287. createUDPAnnRequest(uri::getFieldString(res, USR_HOST, uri.c_str()),
  288. res.port, localPort);
  289. }
  290. else {
  291. treq = createHTTPAnnRequest(btAnnounce_->getAnnounceUrl());
  292. }
  293. btAnnounce_->announceStart(); // inside it, trackers++.
  294. return treq;
  295. }
  296. else {
  297. btAnnounce_->announceFailure();
  298. }
  299. }
  300. if (btAnnounce_->isAllAnnounceFailed()) {
  301. btAnnounce_->resetAnnounce();
  302. }
  303. return nullptr;
  304. }
  305. std::unique_ptr<AnnRequest>
  306. TrackerWatcherCommand::createUDPAnnRequest(const std::string& host,
  307. uint16_t port, uint16_t localPort)
  308. {
  309. auto req = btAnnounce_->createUDPTrackerRequest(host, port, localPort);
  310. req->user_data = this;
  311. return make_unique<UDPAnnRequest>(std::move(req));
  312. }
  313. namespace {
  314. bool backupTrackerIsAvailable(const std::shared_ptr<DownloadContext>& context)
  315. {
  316. auto torrentAttrs = bittorrent::getTorrentAttrs(context);
  317. if (torrentAttrs->announceList.size() >= 2) {
  318. return true;
  319. }
  320. if (torrentAttrs->announceList.empty()) {
  321. return false;
  322. }
  323. if (torrentAttrs->announceList[0].size() >= 2) {
  324. return true;
  325. }
  326. else {
  327. return false;
  328. }
  329. }
  330. } // namespace
  331. std::unique_ptr<AnnRequest>
  332. TrackerWatcherCommand::createHTTPAnnRequest(const std::string& uri)
  333. {
  334. std::vector<std::string> uris;
  335. uris.push_back(uri);
  336. auto option = util::copy(getOption());
  337. auto rg = make_unique<RequestGroup>(GroupId::create(), option);
  338. if (backupTrackerIsAvailable(requestGroup_->getDownloadContext())) {
  339. A2_LOG_DEBUG("This is multi-tracker announce.");
  340. }
  341. else {
  342. A2_LOG_DEBUG("This is single-tracker announce.");
  343. }
  344. rg->setNumConcurrentCommand(1);
  345. // If backup tracker is available, try 2 times for each tracker
  346. // and if they all fails, then try next one.
  347. option->put(PREF_MAX_TRIES, "2");
  348. // TODO When dry-run mode becomes available in BitTorrent, set
  349. // PREF_DRY_RUN=false too.
  350. option->put(PREF_USE_HEAD, A2_V_FALSE);
  351. // Setting tracker timeouts
  352. rg->setTimeout(
  353. std::chrono::seconds(option->getAsInt(PREF_BT_TRACKER_TIMEOUT)));
  354. option->put(PREF_CONNECT_TIMEOUT,
  355. option->get(PREF_BT_TRACKER_CONNECT_TIMEOUT));
  356. option->put(PREF_REUSE_URI, A2_V_FALSE);
  357. option->put(PREF_SELECT_LEAST_USED_HOST, A2_V_FALSE);
  358. auto dctx = std::make_shared<DownloadContext>(
  359. option->getAsInt(PREF_PIECE_LENGTH), 0, "[tracker.announce]");
  360. dctx->getFileEntries().front()->setUris(uris);
  361. rg->setDownloadContext(dctx);
  362. auto dwf = std::make_shared<ByteArrayDiskWriterFactory>();
  363. rg->setDiskWriterFactory(dwf);
  364. rg->setFileAllocationEnabled(false);
  365. rg->setPreLocalFileCheckEnabled(false);
  366. // Clearing pre- and post handler is not needed because the
  367. // RequestGroup is not handled by RequestGroupMan.
  368. rg->clearPreDownloadHandler();
  369. rg->clearPostDownloadHandler();
  370. dctx->setAcceptMetalink(false);
  371. A2_LOG_INFO(fmt("Creating tracker request group GID#%s",
  372. GroupId::toHex(rg->getGID()).c_str()));
  373. return make_unique<HTTPAnnRequest>(std::move(rg));
  374. }
  375. void TrackerWatcherCommand::setBtRuntime(
  376. const std::shared_ptr<BtRuntime>& btRuntime)
  377. {
  378. btRuntime_ = btRuntime;
  379. }
  380. void TrackerWatcherCommand::setPeerStorage(
  381. const std::shared_ptr<PeerStorage>& peerStorage)
  382. {
  383. peerStorage_ = peerStorage;
  384. }
  385. void TrackerWatcherCommand::setPieceStorage(
  386. const std::shared_ptr<PieceStorage>& pieceStorage)
  387. {
  388. pieceStorage_ = pieceStorage;
  389. }
  390. void TrackerWatcherCommand::setBtAnnounce(
  391. const std::shared_ptr<BtAnnounce>& btAnnounce)
  392. {
  393. btAnnounce_ = btAnnounce;
  394. }
  395. const std::shared_ptr<Option>& TrackerWatcherCommand::getOption() const
  396. {
  397. return requestGroup_->getOption();
  398. }
  399. } // namespace aria2