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