download_helper.cc 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568
  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. dctx->getFirstFileEntry()->setPath(torrentAttrs->name);
  236. rg->setDownloadContext(dctx);
  237. rg->clearPostDownloadHandler();
  238. rg->addPostDownloadHandler(
  239. download_handlers::getUTMetadataPostDownloadHandler());
  240. rg->setDiskWriterFactory(std::make_shared<ByteArrayDiskWriterFactory>());
  241. rg->setMetadataInfo(createMetadataInfo(gid, magnetLink));
  242. rg->markInMemoryDownload();
  243. if (option->getAsBool(PREF_ENABLE_RPC)) {
  244. rg->setPauseRequested(option->getAsBool(PREF_PAUSE));
  245. }
  246. removeOneshotOption(option);
  247. return rg;
  248. }
  249. } // namespace
  250. void createRequestGroupForBitTorrent(
  251. std::vector<std::shared_ptr<RequestGroup>>& result,
  252. const std::shared_ptr<Option>& option, const std::vector<std::string>& uris,
  253. const std::string& metaInfoUri, const std::string& torrentData,
  254. bool adjustAnnounceUri)
  255. {
  256. std::unique_ptr<ValueBase> torrent;
  257. bittorrent::ValueBaseBencodeParser parser;
  258. if (torrentData.empty()) {
  259. torrent = parseFile(parser, metaInfoUri);
  260. }
  261. else {
  262. ssize_t error;
  263. torrent = parser.parseFinal(torrentData.c_str(), torrentData.size(), error);
  264. }
  265. if (!torrent) {
  266. throw DL_ABORT_EX2("Bencode decoding failed",
  267. error_code::BENCODE_PARSE_ERROR);
  268. }
  269. createRequestGroupForBitTorrent(result, option, uris, metaInfoUri,
  270. torrent.get(), adjustAnnounceUri);
  271. }
  272. void createRequestGroupForBitTorrent(
  273. std::vector<std::shared_ptr<RequestGroup>>& result,
  274. const std::shared_ptr<Option>& option, const std::vector<std::string>& uris,
  275. const std::string& metaInfoUri, const ValueBase* torrent,
  276. bool adjustAnnounceUri)
  277. {
  278. std::vector<std::string> nargs;
  279. if (option->get(PREF_PARAMETERIZED_URI) == A2_V_TRUE) {
  280. unfoldURI(nargs, uris);
  281. }
  282. else {
  283. nargs = uris;
  284. }
  285. // we ignore -Z option here
  286. size_t numSplit = option->getAsInt(PREF_SPLIT);
  287. auto rg = createBtRequestGroup(metaInfoUri, option, nargs, torrent,
  288. adjustAnnounceUri);
  289. rg->setNumConcurrentCommand(numSplit);
  290. result.push_back(rg);
  291. }
  292. #endif // ENABLE_BITTORRENT
  293. #ifdef ENABLE_METALINK
  294. void createRequestGroupForMetalink(
  295. std::vector<std::shared_ptr<RequestGroup>>& result,
  296. const std::shared_ptr<Option>& option, const std::string& metalinkData)
  297. {
  298. if (metalinkData.empty()) {
  299. Metalink2RequestGroup().generate(result, option->get(PREF_METALINK_FILE),
  300. option,
  301. option->get(PREF_METALINK_BASE_URI));
  302. }
  303. else {
  304. auto dw = std::make_shared<ByteArrayDiskWriter>();
  305. dw->setString(metalinkData);
  306. Metalink2RequestGroup().generate(result, dw, option,
  307. option->get(PREF_METALINK_BASE_URI));
  308. }
  309. }
  310. #endif // ENABLE_METALINK
  311. namespace {
  312. class AccRequestGroup {
  313. private:
  314. std::vector<std::shared_ptr<RequestGroup>>& requestGroups_;
  315. ProtocolDetector detector_;
  316. std::shared_ptr<Option> option_;
  317. bool ignoreLocalPath_;
  318. bool throwOnError_;
  319. public:
  320. AccRequestGroup(std::vector<std::shared_ptr<RequestGroup>>& requestGroups,
  321. std::shared_ptr<Option> option, bool ignoreLocalPath = false,
  322. bool throwOnError = false)
  323. : requestGroups_(requestGroups),
  324. option_(std::move(option)),
  325. ignoreLocalPath_(ignoreLocalPath),
  326. throwOnError_(throwOnError)
  327. {
  328. }
  329. void operator()(const std::string& uri)
  330. {
  331. if (detector_.isStreamProtocol(uri)) {
  332. std::vector<std::string> streamURIs;
  333. size_t numIter = option_->getAsInt(PREF_MAX_CONNECTION_PER_SERVER);
  334. size_t numSplit = option_->getAsInt(PREF_SPLIT);
  335. size_t num = std::min(numIter, numSplit);
  336. for (size_t i = 0; i < num; ++i) {
  337. streamURIs.push_back(uri);
  338. }
  339. auto rg = createRequestGroup(option_, streamURIs);
  340. rg->setNumConcurrentCommand(numSplit);
  341. requestGroups_.push_back(rg);
  342. }
  343. #ifdef ENABLE_BITTORRENT
  344. else if (detector_.guessTorrentMagnet(uri)) {
  345. requestGroups_.push_back(createBtMagnetRequestGroup(uri, option_));
  346. }
  347. else if (!ignoreLocalPath_ && detector_.guessTorrentFile(uri)) {
  348. try {
  349. bittorrent::ValueBaseBencodeParser parser;
  350. auto torrent = parseFile(parser, uri);
  351. if (!torrent) {
  352. throw DL_ABORT_EX2("Bencode decoding failed",
  353. error_code::BENCODE_PARSE_ERROR);
  354. }
  355. requestGroups_.push_back(
  356. createBtRequestGroup(uri, option_, {}, torrent.get()));
  357. }
  358. catch (RecoverableException& e) {
  359. if (throwOnError_) {
  360. throw;
  361. }
  362. else {
  363. // error occurred while parsing torrent file.
  364. // We simply ignore it.
  365. A2_LOG_ERROR_EX(EX_EXCEPTION_CAUGHT, e);
  366. }
  367. }
  368. }
  369. #endif // ENABLE_BITTORRENT
  370. #ifdef ENABLE_METALINK
  371. else if (!ignoreLocalPath_ && detector_.guessMetalinkFile(uri)) {
  372. try {
  373. Metalink2RequestGroup().generate(requestGroups_, uri, option_,
  374. option_->get(PREF_METALINK_BASE_URI));
  375. }
  376. catch (RecoverableException& e) {
  377. if (throwOnError_) {
  378. throw;
  379. }
  380. else {
  381. // error occurred while parsing metalink file.
  382. // We simply ignore it.
  383. A2_LOG_ERROR_EX(EX_EXCEPTION_CAUGHT, e);
  384. }
  385. }
  386. }
  387. #endif // ENABLE_METALINK
  388. else {
  389. if (throwOnError_) {
  390. throw DL_ABORT_EX(fmt(MSG_UNRECOGNIZED_URI, uri.c_str()));
  391. }
  392. else {
  393. A2_LOG_ERROR(fmt(MSG_UNRECOGNIZED_URI, uri.c_str()));
  394. }
  395. }
  396. }
  397. };
  398. } // namespace
  399. namespace {
  400. class StreamProtocolFilter {
  401. private:
  402. ProtocolDetector detector_;
  403. public:
  404. bool operator()(const std::string& uri)
  405. {
  406. return detector_.isStreamProtocol(uri);
  407. }
  408. };
  409. } // namespace
  410. void createRequestGroupForUri(
  411. std::vector<std::shared_ptr<RequestGroup>>& result,
  412. const std::shared_ptr<Option>& option, const std::vector<std::string>& uris,
  413. bool ignoreForceSequential, bool ignoreLocalPath, bool throwOnError)
  414. {
  415. std::vector<std::string> nargs;
  416. if (option->get(PREF_PARAMETERIZED_URI) == A2_V_TRUE) {
  417. unfoldURI(nargs, uris);
  418. }
  419. else {
  420. nargs = uris;
  421. }
  422. if (!ignoreForceSequential &&
  423. option->get(PREF_FORCE_SEQUENTIAL) == A2_V_TRUE) {
  424. std::for_each(
  425. std::begin(nargs), std::end(nargs),
  426. AccRequestGroup(result, option, ignoreLocalPath, throwOnError));
  427. }
  428. else {
  429. auto strmProtoEnd = std::stable_partition(
  430. std::begin(nargs), std::end(nargs), StreamProtocolFilter());
  431. // let's process http/ftp protocols first.
  432. if (std::begin(nargs) != strmProtoEnd) {
  433. size_t numIter = option->getAsInt(PREF_MAX_CONNECTION_PER_SERVER);
  434. size_t numSplit = option->getAsInt(PREF_SPLIT);
  435. std::vector<std::string> streamURIs;
  436. splitURI(streamURIs, std::begin(nargs), strmProtoEnd, numSplit, numIter);
  437. try {
  438. auto rg = createRequestGroup(option, streamURIs, true);
  439. rg->setNumConcurrentCommand(numSplit);
  440. result.push_back(rg);
  441. }
  442. catch (RecoverableException& e) {
  443. if (throwOnError) {
  444. throw;
  445. }
  446. else {
  447. A2_LOG_ERROR_EX(EX_EXCEPTION_CAUGHT, e);
  448. }
  449. }
  450. }
  451. // process remaining URIs(local metalink, BitTorrent files)
  452. std::for_each(
  453. strmProtoEnd, std::end(nargs),
  454. AccRequestGroup(result, option, ignoreLocalPath, throwOnError));
  455. }
  456. }
  457. bool createRequestGroupFromUriListParser(
  458. std::vector<std::shared_ptr<RequestGroup>>& result, const Option* option,
  459. UriListParser* uriListParser)
  460. {
  461. // Since result already contains some entries, we cache the size of
  462. // it. Later, we use this value to determine RequestGroup is
  463. // actually created.
  464. size_t num = result.size();
  465. while (uriListParser->hasNext()) {
  466. std::vector<std::string> uris;
  467. Option tempOption;
  468. uriListParser->parseNext(uris, tempOption);
  469. if (uris.empty()) {
  470. continue;
  471. }
  472. auto requestOption = std::make_shared<Option>(*option);
  473. requestOption->remove(PREF_OUT);
  474. const auto& oparser = OptionParser::getInstance();
  475. for (size_t i = 1, len = option::countOption(); i < len; ++i) {
  476. auto pref = option::i2p(i);
  477. auto h = oparser->find(pref);
  478. if (h && h->getInitialOption() && tempOption.defined(pref)) {
  479. requestOption->put(pref, tempOption.get(pref));
  480. }
  481. }
  482. // This does not throw exception because throwOnError = false.
  483. createRequestGroupForUri(result, requestOption, uris);
  484. if (num < result.size()) {
  485. return true;
  486. }
  487. }
  488. return false;
  489. }
  490. std::shared_ptr<UriListParser> openUriListParser(const std::string& filename)
  491. {
  492. std::string listPath;
  493. if (filename == "-") {
  494. listPath = DEV_STDIN;
  495. }
  496. else {
  497. if (!File(filename).isFile()) {
  498. throw DL_ABORT_EX(fmt(EX_FILE_OPEN, filename.c_str(), "No such file"));
  499. }
  500. listPath = filename;
  501. }
  502. return std::make_shared<UriListParser>(listPath);
  503. }
  504. void createRequestGroupForUriList(
  505. std::vector<std::shared_ptr<RequestGroup>>& result,
  506. const std::shared_ptr<Option>& option)
  507. {
  508. auto uriListParser = openUriListParser(option->get(PREF_INPUT_FILE));
  509. while (createRequestGroupFromUriListParser(result, option.get(),
  510. uriListParser.get()))
  511. ;
  512. }
  513. std::shared_ptr<MetadataInfo> createMetadataInfoFromFirstFileEntry(
  514. const std::shared_ptr<GroupId>& gid,
  515. const std::shared_ptr<DownloadContext>& dctx)
  516. {
  517. if (dctx->getFileEntries().empty()) {
  518. return nullptr;
  519. }
  520. else {
  521. auto uris = dctx->getFileEntries()[0]->getUris();
  522. if (uris.empty()) {
  523. return nullptr;
  524. }
  525. return std::make_shared<MetadataInfo>(gid, uris[0]);
  526. }
  527. }
  528. void removeOneshotOption(const std::shared_ptr<Option>& option)
  529. {
  530. option->remove(PREF_PAUSE);
  531. option->remove(PREF_GID);
  532. }
  533. } // namespace aria2