download_helper.cc 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572
  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 "download_helper.h"
  36. #include <algorithm>
  37. #include <sstream>
  38. #include "RequestGroup.h"
  39. #include "Option.h"
  40. #include "prefs.h"
  41. #include "Metalink2RequestGroup.h"
  42. #include "ProtocolDetector.h"
  43. #include "paramed_string.h"
  44. #include "UriListParser.h"
  45. #include "DownloadContext.h"
  46. #include "RecoverableException.h"
  47. #include "DlAbortEx.h"
  48. #include "message.h"
  49. #include "fmt.h"
  50. #include "FileEntry.h"
  51. #include "LogFactory.h"
  52. #include "File.h"
  53. #include "util.h"
  54. #include "array_fun.h"
  55. #include "OptionHandler.h"
  56. #include "ByteArrayDiskWriter.h"
  57. #include "a2functional.h"
  58. #include "ByteArrayDiskWriterFactory.h"
  59. #include "MetadataInfo.h"
  60. #include "OptionParser.h"
  61. #include "SegList.h"
  62. #include "download_handlers.h"
  63. #include "SimpleRandomizer.h"
  64. #ifdef ENABLE_BITTORRENT
  65. #include "bittorrent_helper.h"
  66. #include "BtConstants.h"
  67. #include "ValueBaseBencodeParser.h"
  68. #endif // ENABLE_BITTORRENT
  69. namespace aria2 {
  70. namespace {
  71. void unfoldURI(std::vector<std::string>& result,
  72. const std::vector<std::string>& args)
  73. {
  74. for (const auto& i : args) {
  75. paramed_string::expand(std::begin(i), std::end(i),
  76. std::back_inserter(result));
  77. }
  78. }
  79. } // namespace
  80. namespace {
  81. template <typename InputIterator>
  82. void splitURI(std::vector<std::string>& result, InputIterator begin,
  83. InputIterator end, size_t numSplit, size_t maxIter)
  84. {
  85. size_t numURIs = std::distance(begin, end);
  86. if (numURIs >= numSplit) {
  87. result.insert(std::end(result), begin, end);
  88. }
  89. else if (numURIs > 0) {
  90. size_t num = std::min(numSplit / numURIs, maxIter);
  91. for (size_t i = 0; i < num; ++i) {
  92. result.insert(std::end(result), begin, end);
  93. }
  94. if (num < maxIter) {
  95. result.insert(std::end(result), begin, begin + (numSplit % numURIs));
  96. }
  97. }
  98. }
  99. } // namespace
  100. namespace {
  101. std::shared_ptr<GroupId> getGID(const std::shared_ptr<Option>& option)
  102. {
  103. std::shared_ptr<GroupId> gid;
  104. if (option->defined(PREF_GID)) {
  105. a2_gid_t n;
  106. if (GroupId::toNumericId(n, option->get(PREF_GID).c_str()) != 0) {
  107. throw DL_ABORT_EX(
  108. fmt("%s is invalid for GID.", option->get(PREF_GID).c_str()));
  109. }
  110. gid = GroupId::import(n);
  111. if (!gid) {
  112. throw DL_ABORT_EX(
  113. fmt("GID %s is not unique.", option->get(PREF_GID).c_str()));
  114. }
  115. }
  116. else {
  117. gid = GroupId::create();
  118. }
  119. return gid;
  120. }
  121. } // namespace
  122. namespace {
  123. std::shared_ptr<RequestGroup>
  124. createRequestGroup(const std::shared_ptr<Option>& optionTemplate,
  125. const std::vector<std::string>& uris,
  126. bool useOutOption = false)
  127. {
  128. auto option = util::copy(optionTemplate);
  129. auto rg = std::make_shared<RequestGroup>(getGID(option), option);
  130. auto dctx = std::make_shared<DownloadContext>(
  131. option->getAsInt(PREF_PIECE_LENGTH), 0,
  132. useOutOption && !option->blank(PREF_OUT)
  133. ? util::applyDir(option->get(PREF_DIR), option->get(PREF_OUT))
  134. : A2STR::NIL);
  135. dctx->getFirstFileEntry()->setUris(uris);
  136. dctx->getFirstFileEntry()->setMaxConnectionPerServer(
  137. option->getAsInt(PREF_MAX_CONNECTION_PER_SERVER));
  138. const std::string& checksum = option->get(PREF_CHECKSUM);
  139. if (!checksum.empty()) {
  140. auto p = util::divide(std::begin(checksum), std::end(checksum), '=');
  141. std::string hashType(p.first.first, p.first.second);
  142. std::string hexDigest(p.second.first, p.second.second);
  143. util::lowercase(hashType);
  144. dctx->setDigest(hashType,
  145. util::fromHex(std::begin(hexDigest), std::end(hexDigest)));
  146. }
  147. rg->setDownloadContext(dctx);
  148. if (option->getAsBool(PREF_ENABLE_RPC)) {
  149. rg->setPauseRequested(option->getAsBool(PREF_PAUSE));
  150. }
  151. removeOneshotOption(option);
  152. return rg;
  153. }
  154. } // namespace
  155. #if defined(ENABLE_BITTORRENT) || defined(ENABLE_METALINK)
  156. namespace {
  157. std::shared_ptr<MetadataInfo>
  158. createMetadataInfo(const std::shared_ptr<GroupId>& gid, const std::string& uri)
  159. {
  160. return std::make_shared<MetadataInfo>(gid, uri);
  161. }
  162. } // namespace
  163. namespace {
  164. std::shared_ptr<MetadataInfo> createMetadataInfoDataOnly()
  165. {
  166. return std::make_shared<MetadataInfo>();
  167. }
  168. } // namespace
  169. #endif // ENABLE_BITTORRENT || ENABLE_METALINK
  170. #ifdef ENABLE_BITTORRENT
  171. namespace {
  172. std::shared_ptr<RequestGroup>
  173. createBtRequestGroup(const std::string& metaInfoUri,
  174. const std::shared_ptr<Option>& optionTemplate,
  175. const std::vector<std::string>& auxUris,
  176. const ValueBase* torrent, bool adjustAnnounceUri = true)
  177. {
  178. auto option = util::copy(optionTemplate);
  179. auto gid = getGID(option);
  180. auto rg = std::make_shared<RequestGroup>(gid, option);
  181. auto dctx = std::make_shared<DownloadContext>();
  182. // may throw exception
  183. bittorrent::loadFromMemory(torrent, dctx, option, auxUris,
  184. metaInfoUri.empty() ? "default" : metaInfoUri);
  185. for (auto& fe : dctx->getFileEntries()) {
  186. auto& uris = fe->getRemainingUris();
  187. std::shuffle(std::begin(uris), std::end(uris),
  188. *SimpleRandomizer::getInstance());
  189. }
  190. if (metaInfoUri.empty()) {
  191. rg->setMetadataInfo(createMetadataInfoDataOnly());
  192. }
  193. else {
  194. rg->setMetadataInfo(createMetadataInfo(gid, metaInfoUri));
  195. }
  196. if (adjustAnnounceUri) {
  197. bittorrent::adjustAnnounceUri(bittorrent::getTorrentAttrs(dctx), option);
  198. }
  199. auto sgl = util::parseIntSegments(option->get(PREF_SELECT_FILE));
  200. sgl.normalize();
  201. dctx->setFileFilter(std::move(sgl));
  202. std::istringstream indexOutIn(option->get(PREF_INDEX_OUT));
  203. auto indexPaths = util::createIndexPaths(indexOutIn);
  204. for (const auto& i : indexPaths) {
  205. dctx->setFilePathWithIndex(i.first,
  206. util::applyDir(option->get(PREF_DIR), i.second));
  207. }
  208. rg->setDownloadContext(dctx);
  209. if (option->getAsBool(PREF_ENABLE_RPC)) {
  210. rg->setPauseRequested(option->getAsBool(PREF_PAUSE));
  211. }
  212. // Remove "metalink" from Accept Type list to avoid server from
  213. // responding Metalink file for web-seeding URIs.
  214. dctx->setAcceptMetalink(false);
  215. removeOneshotOption(option);
  216. return rg;
  217. }
  218. } // namespace
  219. namespace {
  220. std::shared_ptr<RequestGroup>
  221. createBtMagnetRequestGroup(const std::string& magnetLink,
  222. const std::shared_ptr<Option>& optionTemplate)
  223. {
  224. auto option = util::copy(optionTemplate);
  225. auto gid = getGID(option);
  226. auto rg = std::make_shared<RequestGroup>(gid, option);
  227. auto dctx = std::make_shared<DownloadContext>(METADATA_PIECE_SIZE, 0);
  228. // We only know info hash. Total Length is unknown at this moment.
  229. dctx->markTotalLengthIsUnknown();
  230. rg->setFileAllocationEnabled(false);
  231. rg->setPreLocalFileCheckEnabled(false);
  232. bittorrent::loadMagnet(magnetLink, dctx);
  233. auto torrentAttrs = bittorrent::getTorrentAttrs(dctx);
  234. bittorrent::adjustAnnounceUri(torrentAttrs, option);
  235. // torrentAttrs->name may contain "/", but we use basename of
  236. // FileEntry::getPath() to print out in-memory download entry.
  237. // Since "/" is treated as separator, we replace it with "-".
  238. dctx->getFirstFileEntry()->setPath(
  239. util::replace(torrentAttrs->name, "/", "-"));
  240. rg->setDownloadContext(dctx);
  241. rg->clearPostDownloadHandler();
  242. rg->addPostDownloadHandler(
  243. download_handlers::getUTMetadataPostDownloadHandler());
  244. rg->setDiskWriterFactory(std::make_shared<ByteArrayDiskWriterFactory>());
  245. rg->setMetadataInfo(createMetadataInfo(gid, magnetLink));
  246. rg->markInMemoryDownload();
  247. if (option->getAsBool(PREF_ENABLE_RPC)) {
  248. rg->setPauseRequested(option->getAsBool(PREF_PAUSE));
  249. }
  250. removeOneshotOption(option);
  251. return rg;
  252. }
  253. } // namespace
  254. void createRequestGroupForBitTorrent(
  255. std::vector<std::shared_ptr<RequestGroup>>& result,
  256. const std::shared_ptr<Option>& option, const std::vector<std::string>& uris,
  257. const std::string& metaInfoUri, const std::string& torrentData,
  258. bool adjustAnnounceUri)
  259. {
  260. std::unique_ptr<ValueBase> torrent;
  261. bittorrent::ValueBaseBencodeParser parser;
  262. if (torrentData.empty()) {
  263. torrent = parseFile(parser, metaInfoUri);
  264. }
  265. else {
  266. ssize_t error;
  267. torrent = parser.parseFinal(torrentData.c_str(), torrentData.size(), error);
  268. }
  269. if (!torrent) {
  270. throw DL_ABORT_EX2("Bencode decoding failed",
  271. error_code::BENCODE_PARSE_ERROR);
  272. }
  273. createRequestGroupForBitTorrent(result, option, uris, metaInfoUri,
  274. torrent.get(), adjustAnnounceUri);
  275. }
  276. void createRequestGroupForBitTorrent(
  277. std::vector<std::shared_ptr<RequestGroup>>& result,
  278. const std::shared_ptr<Option>& option, const std::vector<std::string>& uris,
  279. const std::string& metaInfoUri, const ValueBase* torrent,
  280. bool adjustAnnounceUri)
  281. {
  282. std::vector<std::string> nargs;
  283. if (option->get(PREF_PARAMETERIZED_URI) == A2_V_TRUE) {
  284. unfoldURI(nargs, uris);
  285. }
  286. else {
  287. nargs = uris;
  288. }
  289. // we ignore -Z option here
  290. size_t numSplit = option->getAsInt(PREF_SPLIT);
  291. auto rg = createBtRequestGroup(metaInfoUri, option, nargs, torrent,
  292. adjustAnnounceUri);
  293. rg->setNumConcurrentCommand(numSplit);
  294. result.push_back(rg);
  295. }
  296. #endif // ENABLE_BITTORRENT
  297. #ifdef ENABLE_METALINK
  298. void createRequestGroupForMetalink(
  299. std::vector<std::shared_ptr<RequestGroup>>& result,
  300. const std::shared_ptr<Option>& option, const std::string& metalinkData)
  301. {
  302. if (metalinkData.empty()) {
  303. Metalink2RequestGroup().generate(result, option->get(PREF_METALINK_FILE),
  304. option,
  305. option->get(PREF_METALINK_BASE_URI));
  306. }
  307. else {
  308. auto dw = std::make_shared<ByteArrayDiskWriter>();
  309. dw->setString(metalinkData);
  310. Metalink2RequestGroup().generate(result, dw, option,
  311. option->get(PREF_METALINK_BASE_URI));
  312. }
  313. }
  314. #endif // ENABLE_METALINK
  315. namespace {
  316. class AccRequestGroup {
  317. private:
  318. std::vector<std::shared_ptr<RequestGroup>>& requestGroups_;
  319. ProtocolDetector detector_;
  320. std::shared_ptr<Option> option_;
  321. bool ignoreLocalPath_;
  322. bool throwOnError_;
  323. public:
  324. AccRequestGroup(std::vector<std::shared_ptr<RequestGroup>>& requestGroups,
  325. std::shared_ptr<Option> option, bool ignoreLocalPath = false,
  326. bool throwOnError = false)
  327. : requestGroups_(requestGroups),
  328. option_(std::move(option)),
  329. ignoreLocalPath_(ignoreLocalPath),
  330. throwOnError_(throwOnError)
  331. {
  332. }
  333. void operator()(const std::string& uri)
  334. {
  335. if (detector_.isStreamProtocol(uri)) {
  336. std::vector<std::string> streamURIs;
  337. size_t numIter = option_->getAsInt(PREF_MAX_CONNECTION_PER_SERVER);
  338. size_t numSplit = option_->getAsInt(PREF_SPLIT);
  339. size_t num = std::min(numIter, numSplit);
  340. for (size_t i = 0; i < num; ++i) {
  341. streamURIs.push_back(uri);
  342. }
  343. auto rg = createRequestGroup(option_, streamURIs);
  344. rg->setNumConcurrentCommand(numSplit);
  345. requestGroups_.push_back(rg);
  346. }
  347. #ifdef ENABLE_BITTORRENT
  348. else if (detector_.guessTorrentMagnet(uri)) {
  349. requestGroups_.push_back(createBtMagnetRequestGroup(uri, option_));
  350. }
  351. else if (!ignoreLocalPath_ && detector_.guessTorrentFile(uri)) {
  352. try {
  353. bittorrent::ValueBaseBencodeParser parser;
  354. auto torrent = parseFile(parser, uri);
  355. if (!torrent) {
  356. throw DL_ABORT_EX2("Bencode decoding failed",
  357. error_code::BENCODE_PARSE_ERROR);
  358. }
  359. requestGroups_.push_back(
  360. createBtRequestGroup(uri, option_, {}, torrent.get()));
  361. }
  362. catch (RecoverableException& e) {
  363. if (throwOnError_) {
  364. throw;
  365. }
  366. else {
  367. // error occurred while parsing torrent file.
  368. // We simply ignore it.
  369. A2_LOG_ERROR_EX(EX_EXCEPTION_CAUGHT, e);
  370. }
  371. }
  372. }
  373. #endif // ENABLE_BITTORRENT
  374. #ifdef ENABLE_METALINK
  375. else if (!ignoreLocalPath_ && detector_.guessMetalinkFile(uri)) {
  376. try {
  377. Metalink2RequestGroup().generate(requestGroups_, uri, option_,
  378. option_->get(PREF_METALINK_BASE_URI));
  379. }
  380. catch (RecoverableException& e) {
  381. if (throwOnError_) {
  382. throw;
  383. }
  384. else {
  385. // error occurred while parsing metalink file.
  386. // We simply ignore it.
  387. A2_LOG_ERROR_EX(EX_EXCEPTION_CAUGHT, e);
  388. }
  389. }
  390. }
  391. #endif // ENABLE_METALINK
  392. else {
  393. if (throwOnError_) {
  394. throw DL_ABORT_EX(fmt(MSG_UNRECOGNIZED_URI, uri.c_str()));
  395. }
  396. else {
  397. A2_LOG_ERROR(fmt(MSG_UNRECOGNIZED_URI, uri.c_str()));
  398. }
  399. }
  400. }
  401. };
  402. } // namespace
  403. namespace {
  404. class StreamProtocolFilter {
  405. private:
  406. ProtocolDetector detector_;
  407. public:
  408. bool operator()(const std::string& uri)
  409. {
  410. return detector_.isStreamProtocol(uri);
  411. }
  412. };
  413. } // namespace
  414. void createRequestGroupForUri(
  415. std::vector<std::shared_ptr<RequestGroup>>& result,
  416. const std::shared_ptr<Option>& option, const std::vector<std::string>& uris,
  417. bool ignoreForceSequential, bool ignoreLocalPath, bool throwOnError)
  418. {
  419. std::vector<std::string> nargs;
  420. if (option->get(PREF_PARAMETERIZED_URI) == A2_V_TRUE) {
  421. unfoldURI(nargs, uris);
  422. }
  423. else {
  424. nargs = uris;
  425. }
  426. if (!ignoreForceSequential &&
  427. option->get(PREF_FORCE_SEQUENTIAL) == A2_V_TRUE) {
  428. std::for_each(
  429. std::begin(nargs), std::end(nargs),
  430. AccRequestGroup(result, option, ignoreLocalPath, throwOnError));
  431. }
  432. else {
  433. auto strmProtoEnd = std::stable_partition(
  434. std::begin(nargs), std::end(nargs), StreamProtocolFilter());
  435. // let's process http/ftp protocols first.
  436. if (std::begin(nargs) != strmProtoEnd) {
  437. size_t numIter = option->getAsInt(PREF_MAX_CONNECTION_PER_SERVER);
  438. size_t numSplit = option->getAsInt(PREF_SPLIT);
  439. std::vector<std::string> streamURIs;
  440. splitURI(streamURIs, std::begin(nargs), strmProtoEnd, numSplit, numIter);
  441. try {
  442. auto rg = createRequestGroup(option, streamURIs, true);
  443. rg->setNumConcurrentCommand(numSplit);
  444. result.push_back(rg);
  445. }
  446. catch (RecoverableException& e) {
  447. if (throwOnError) {
  448. throw;
  449. }
  450. else {
  451. A2_LOG_ERROR_EX(EX_EXCEPTION_CAUGHT, e);
  452. }
  453. }
  454. }
  455. // process remaining URIs(local metalink, BitTorrent files)
  456. std::for_each(
  457. strmProtoEnd, std::end(nargs),
  458. AccRequestGroup(result, option, ignoreLocalPath, throwOnError));
  459. }
  460. }
  461. bool createRequestGroupFromUriListParser(
  462. std::vector<std::shared_ptr<RequestGroup>>& result, const Option* option,
  463. UriListParser* uriListParser)
  464. {
  465. // Since result already contains some entries, we cache the size of
  466. // it. Later, we use this value to determine RequestGroup is
  467. // actually created.
  468. size_t num = result.size();
  469. while (uriListParser->hasNext()) {
  470. std::vector<std::string> uris;
  471. Option tempOption;
  472. uriListParser->parseNext(uris, tempOption);
  473. if (uris.empty()) {
  474. continue;
  475. }
  476. auto requestOption = std::make_shared<Option>(*option);
  477. requestOption->remove(PREF_OUT);
  478. const auto& oparser = OptionParser::getInstance();
  479. for (size_t i = 1, len = option::countOption(); i < len; ++i) {
  480. auto pref = option::i2p(i);
  481. auto h = oparser->find(pref);
  482. if (h && h->getInitialOption() && tempOption.defined(pref)) {
  483. requestOption->put(pref, tempOption.get(pref));
  484. }
  485. }
  486. // This does not throw exception because throwOnError = false.
  487. createRequestGroupForUri(result, requestOption, uris);
  488. if (num < result.size()) {
  489. return true;
  490. }
  491. }
  492. return false;
  493. }
  494. std::shared_ptr<UriListParser> openUriListParser(const std::string& filename)
  495. {
  496. std::string listPath;
  497. if (filename == "-") {
  498. listPath = DEV_STDIN;
  499. }
  500. else {
  501. if (!File(filename).isFile()) {
  502. throw DL_ABORT_EX(fmt(EX_FILE_OPEN, filename.c_str(), "No such file"));
  503. }
  504. listPath = filename;
  505. }
  506. return std::make_shared<UriListParser>(listPath);
  507. }
  508. void createRequestGroupForUriList(
  509. std::vector<std::shared_ptr<RequestGroup>>& result,
  510. const std::shared_ptr<Option>& option)
  511. {
  512. auto uriListParser = openUriListParser(option->get(PREF_INPUT_FILE));
  513. while (createRequestGroupFromUriListParser(result, option.get(),
  514. uriListParser.get()))
  515. ;
  516. }
  517. std::shared_ptr<MetadataInfo> createMetadataInfoFromFirstFileEntry(
  518. const std::shared_ptr<GroupId>& gid,
  519. const std::shared_ptr<DownloadContext>& dctx)
  520. {
  521. if (dctx->getFileEntries().empty()) {
  522. return nullptr;
  523. }
  524. else {
  525. auto uris = dctx->getFileEntries()[0]->getUris();
  526. if (uris.empty()) {
  527. return nullptr;
  528. }
  529. return std::make_shared<MetadataInfo>(gid, uris[0]);
  530. }
  531. }
  532. void removeOneshotOption(const std::shared_ptr<Option>& option)
  533. {
  534. option->remove(PREF_PAUSE);
  535. option->remove(PREF_GID);
  536. }
  537. } // namespace aria2