download_helper.cc 17 KB

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