download_helper.cc 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511
  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 <iostream>
  37. #include <fstream>
  38. #include <algorithm>
  39. #include <sstream>
  40. #include "RequestGroup.h"
  41. #include "Option.h"
  42. #include "prefs.h"
  43. #include "Metalink2RequestGroup.h"
  44. #include "ProtocolDetector.h"
  45. #include "ParameterizedStringParser.h"
  46. #include "PStringBuildVisitor.h"
  47. #include "UriListParser.h"
  48. #include "DownloadContext.h"
  49. #include "RecoverableException.h"
  50. #include "DlAbortEx.h"
  51. #include "message.h"
  52. #include "StringFormat.h"
  53. #include "FileEntry.h"
  54. #include "LogFactory.h"
  55. #include "File.h"
  56. #include "util.h"
  57. #include "array_fun.h"
  58. #include "OptionHandler.h"
  59. #include "ByteArrayDiskWriter.h"
  60. #include "a2functional.h"
  61. #include "ByteArrayDiskWriterFactory.h"
  62. #include "MetadataInfo.h"
  63. #ifdef ENABLE_BITTORRENT
  64. # include "bittorrent_helper.h"
  65. # include "BtConstants.h"
  66. # include "UTMetadataPostDownloadHandler.h"
  67. #endif // ENABLE_BITTORRENT
  68. namespace aria2 {
  69. const std::set<std::string>& listRequestOptions()
  70. {
  71. static const std::string REQUEST_OPTIONS[] = {
  72. PREF_DIR,
  73. PREF_CHECK_INTEGRITY,
  74. PREF_CONTINUE,
  75. PREF_ALL_PROXY,
  76. PREF_ALL_PROXY_USER,
  77. PREF_ALL_PROXY_PASSWD,
  78. PREF_CONNECT_TIMEOUT,
  79. PREF_DRY_RUN,
  80. PREF_LOWEST_SPEED_LIMIT,
  81. PREF_MAX_FILE_NOT_FOUND,
  82. PREF_MAX_TRIES,
  83. PREF_NO_PROXY,
  84. PREF_OUT,
  85. PREF_PROXY_METHOD,
  86. PREF_REMOTE_TIME,
  87. PREF_SPLIT,
  88. PREF_TIMEOUT,
  89. PREF_HTTP_AUTH_CHALLENGE,
  90. PREF_HTTP_NO_CACHE,
  91. PREF_HTTP_USER,
  92. PREF_HTTP_PASSWD,
  93. PREF_HTTP_PROXY,
  94. PREF_HTTP_PROXY_USER,
  95. PREF_HTTP_PROXY_PASSWD,
  96. PREF_HTTPS_PROXY,
  97. PREF_HTTPS_PROXY_USER,
  98. PREF_HTTPS_PROXY_PASSWD,
  99. PREF_REFERER,
  100. PREF_ENABLE_HTTP_KEEP_ALIVE,
  101. PREF_ENABLE_HTTP_PIPELINING,
  102. PREF_HEADER,
  103. PREF_USE_HEAD,
  104. PREF_USER_AGENT,
  105. PREF_FTP_USER,
  106. PREF_FTP_PASSWD,
  107. PREF_FTP_PASV,
  108. PREF_FTP_PROXY,
  109. PREF_FTP_PROXY_USER,
  110. PREF_FTP_PROXY_PASSWD,
  111. PREF_FTP_TYPE,
  112. PREF_FTP_REUSE_CONNECTION,
  113. PREF_NO_NETRC,
  114. PREF_REUSE_URI,
  115. PREF_SELECT_FILE,
  116. PREF_BT_ENABLE_LPD,
  117. PREF_BT_EXTERNAL_IP,
  118. PREF_BT_HASH_CHECK_SEED,
  119. PREF_BT_MAX_OPEN_FILES,
  120. PREF_BT_MAX_PEERS,
  121. PREF_BT_METADATA_ONLY,
  122. PREF_BT_MIN_CRYPTO_LEVEL,
  123. PREF_BT_PRIORITIZE_PIECE,
  124. PREF_BT_REQUIRE_CRYPTO,
  125. PREF_BT_REQUEST_PEER_SPEED_LIMIT,
  126. PREF_BT_SAVE_METADATA,
  127. PREF_BT_SEED_UNVERIFIED,
  128. PREF_BT_STOP_TIMEOUT,
  129. PREF_BT_TRACKER_INTERVAL,
  130. PREF_BT_TRACKER_TIMEOUT,
  131. PREF_BT_TRACKER_CONNECT_TIMEOUT,
  132. PREF_ENABLE_PEER_EXCHANGE,
  133. PREF_FOLLOW_TORRENT,
  134. PREF_INDEX_OUT,
  135. PREF_MAX_UPLOAD_LIMIT,
  136. PREF_SEED_RATIO,
  137. PREF_SEED_TIME,
  138. PREF_FOLLOW_METALINK,
  139. PREF_METALINK_SERVERS,
  140. PREF_METALINK_LANGUAGE,
  141. PREF_METALINK_LOCATION,
  142. PREF_METALINK_OS,
  143. PREF_METALINK_VERSION,
  144. PREF_METALINK_PREFERRED_PROTOCOL,
  145. PREF_METALINK_ENABLE_UNIQUE_PROTOCOL,
  146. PREF_ALLOW_OVERWRITE,
  147. PREF_ALLOW_PIECE_LENGTH_CHANGE,
  148. PREF_ASYNC_DNS,
  149. PREF_AUTO_FILE_RENAMING,
  150. PREF_FILE_ALLOCATION,
  151. PREF_MAX_DOWNLOAD_LIMIT,
  152. PREF_NO_FILE_ALLOCATION_LIMIT,
  153. PREF_PARAMETERIZED_URI,
  154. PREF_REALTIME_CHUNK_CHECKSUM,
  155. PREF_REMOVE_CONTROL_FILE,
  156. PREF_ALWAYS_RESUME,
  157. PREF_MAX_RESUME_FAILURE_TRIES,
  158. PREF_HTTP_ACCEPT_GZIP
  159. };
  160. static std::set<std::string> requestOptions
  161. (vbegin(REQUEST_OPTIONS), vend(REQUEST_OPTIONS));
  162. return requestOptions;
  163. }
  164. static void unfoldURI
  165. (std::vector<std::string>& result, const std::vector<std::string>& args)
  166. {
  167. ParameterizedStringParser p;
  168. PStringBuildVisitor v;
  169. for(std::vector<std::string>::const_iterator itr = args.begin(),
  170. eoi = args.end(); itr != eoi; ++itr) {
  171. v.reset();
  172. p.parse(*itr)->accept(v);
  173. result.insert(result.end(), v.getURIs().begin(), v.getURIs().end());
  174. }
  175. }
  176. template<typename InputIterator>
  177. static void splitURI(std::vector<std::string>& result,
  178. InputIterator begin,
  179. InputIterator end,
  180. size_t numSplit,
  181. size_t maxIter)
  182. {
  183. size_t numURIs = std::distance(begin, end);
  184. if(numURIs >= numSplit) {
  185. result.insert(result.end(), begin, end);
  186. } else if(numURIs > 0) {
  187. size_t num = std::min(numSplit/numURIs, maxIter);
  188. for(size_t i = 0; i < num; ++i) {
  189. result.insert(result.end(), begin, end);
  190. }
  191. if(num < maxIter) {
  192. result.insert(result.end(), begin, begin+(numSplit%numURIs));
  193. }
  194. }
  195. }
  196. static SharedHandle<RequestGroup> createRequestGroup
  197. (const SharedHandle<Option>& option, const std::vector<std::string>& uris,
  198. bool useOutOption = false)
  199. {
  200. SharedHandle<RequestGroup> rg(new RequestGroup(option));
  201. SharedHandle<DownloadContext> dctx
  202. (new DownloadContext
  203. (option->getAsInt(PREF_SEGMENT_SIZE),
  204. 0,
  205. useOutOption&&!option->blank(PREF_OUT)?
  206. util::applyDir(option->get(PREF_DIR), option->get(PREF_OUT)):A2STR::NIL));
  207. dctx->setDir(option->get(PREF_DIR));
  208. dctx->getFirstFileEntry()->setUris(uris);
  209. dctx->getFirstFileEntry()->setMaxConnectionPerServer
  210. (option->getAsInt(PREF_MAX_CONNECTION_PER_SERVER));
  211. rg->setDownloadContext(dctx);
  212. return rg;
  213. }
  214. static SharedHandle<MetadataInfo> createMetadataInfo(const std::string& uri)
  215. {
  216. return SharedHandle<MetadataInfo>(new MetadataInfo(uri));
  217. }
  218. static SharedHandle<MetadataInfo> createMetadataInfoDataOnly()
  219. {
  220. return SharedHandle<MetadataInfo>(new MetadataInfo());
  221. }
  222. #ifdef ENABLE_BITTORRENT
  223. static
  224. SharedHandle<RequestGroup>
  225. createBtRequestGroup(const std::string& torrentFilePath,
  226. const SharedHandle<Option>& option,
  227. const std::vector<std::string>& auxUris,
  228. const std::string& torrentData = "")
  229. {
  230. SharedHandle<RequestGroup> rg(new RequestGroup(option));
  231. SharedHandle<DownloadContext> dctx(new DownloadContext());
  232. dctx->setDir(option->get(PREF_DIR));
  233. if(torrentData.empty()) {
  234. bittorrent::load(torrentFilePath, dctx, auxUris);// may throw exception
  235. rg->setMetadataInfo(createMetadataInfo(torrentFilePath));
  236. } else {
  237. bittorrent::loadFromMemory(torrentData, dctx, auxUris, "default"); // may
  238. // throw
  239. // exception
  240. rg->setMetadataInfo(createMetadataInfoDataOnly());
  241. }
  242. dctx->setFileFilter(util::parseIntRange(option->get(PREF_SELECT_FILE)));
  243. std::istringstream indexOutIn(option->get(PREF_INDEX_OUT));
  244. std::map<size_t, std::string> indexPathMap =
  245. util::createIndexPathMap(indexOutIn);
  246. for(std::map<size_t, std::string>::const_iterator i = indexPathMap.begin(),
  247. eoi = indexPathMap.end(); i != eoi; ++i) {
  248. dctx->setFilePathWithIndex
  249. ((*i).first, util::applyDir(dctx->getDir(), (*i).second));
  250. }
  251. rg->setDownloadContext(dctx);
  252. // Remove "metalink" from Accept Type list to avoid server from
  253. // responding Metalink file for web-seeding URIs.
  254. util::removeMetalinkContentTypes(rg);
  255. return rg;
  256. }
  257. static
  258. SharedHandle<RequestGroup>
  259. createBtMagnetRequestGroup(const std::string& magnetLink,
  260. const SharedHandle<Option>& option,
  261. const std::vector<std::string>& auxUris)
  262. {
  263. SharedHandle<RequestGroup> rg(new RequestGroup(option));
  264. SharedHandle<DownloadContext> dctx
  265. (new DownloadContext(METADATA_PIECE_SIZE, 0,
  266. A2STR::NIL));
  267. dctx->setDir(A2STR::NIL);
  268. // We only know info hash. Total Length is unknown at this moment.
  269. dctx->markTotalLengthIsUnknown();
  270. rg->setFileAllocationEnabled(false);
  271. rg->setPreLocalFileCheckEnabled(false);
  272. bittorrent::loadMagnet(magnetLink, dctx);
  273. SharedHandle<TorrentAttribute> torrentAttrs =
  274. bittorrent::getTorrentAttrs(dctx);
  275. dctx->getFirstFileEntry()->setPath(torrentAttrs->name);
  276. rg->setDownloadContext(dctx);
  277. rg->clearPostDownloadHandler();
  278. rg->addPostDownloadHandler
  279. (SharedHandle<UTMetadataPostDownloadHandler>
  280. (new UTMetadataPostDownloadHandler()));
  281. rg->setDiskWriterFactory
  282. (SharedHandle<DiskWriterFactory>(new ByteArrayDiskWriterFactory()));
  283. rg->setMetadataInfo(createMetadataInfo(magnetLink));
  284. return rg;
  285. }
  286. void createRequestGroupForBitTorrent
  287. (std::vector<SharedHandle<RequestGroup> >& result,
  288. const SharedHandle<Option>& option,
  289. const std::vector<std::string>& uris,
  290. const std::string& torrentData)
  291. {
  292. std::vector<std::string> nargs;
  293. if(option->get(PREF_PARAMETERIZED_URI) == V_TRUE) {
  294. unfoldURI(nargs, uris);
  295. } else {
  296. nargs = uris;
  297. }
  298. // we ignore -Z option here
  299. size_t numSplit = option->getAsInt(PREF_SPLIT);
  300. SharedHandle<RequestGroup> rg =
  301. createBtRequestGroup(option->get(PREF_TORRENT_FILE), option, nargs,
  302. torrentData);
  303. rg->setNumConcurrentCommand(numSplit);
  304. result.push_back(rg);
  305. }
  306. #endif // ENABLE_BITTORRENT
  307. #ifdef ENABLE_METALINK
  308. void createRequestGroupForMetalink
  309. (std::vector<SharedHandle<RequestGroup> >& result,
  310. const SharedHandle<Option>& option,
  311. const std::string& metalinkData)
  312. {
  313. if(metalinkData.empty()) {
  314. Metalink2RequestGroup().generate(result,
  315. option->get(PREF_METALINK_FILE),
  316. option);
  317. } else {
  318. SharedHandle<ByteArrayDiskWriter> dw(new ByteArrayDiskWriter());
  319. dw->setString(metalinkData);
  320. Metalink2RequestGroup().generate(result, dw, option);
  321. }
  322. }
  323. #endif // ENABLE_METALINK
  324. class AccRequestGroup {
  325. private:
  326. std::vector<SharedHandle<RequestGroup> >& requestGroups_;
  327. ProtocolDetector detector_;
  328. SharedHandle<Option> option_;
  329. bool ignoreLocalPath_;
  330. public:
  331. AccRequestGroup(std::vector<SharedHandle<RequestGroup> >& requestGroups,
  332. const SharedHandle<Option>& option,
  333. bool ignoreLocalPath = false):
  334. requestGroups_(requestGroups), option_(option),
  335. ignoreLocalPath_(ignoreLocalPath) {}
  336. void
  337. operator()(const std::string& uri)
  338. {
  339. if(detector_.isStreamProtocol(uri)) {
  340. std::vector<std::string> streamURIs;
  341. size_t numIter = option_->getAsInt(PREF_MAX_CONNECTION_PER_SERVER);
  342. size_t numSplit = option_->getAsInt(PREF_SPLIT);
  343. size_t num = std::min(numIter, numSplit);
  344. for(size_t i = 0; i < num; ++i) {
  345. streamURIs.push_back(uri);
  346. }
  347. SharedHandle<RequestGroup> rg = createRequestGroup(option_, streamURIs);
  348. rg->setNumConcurrentCommand(numSplit);
  349. requestGroups_.push_back(rg);
  350. }
  351. #ifdef ENABLE_BITTORRENT
  352. else if(detector_.guessTorrentMagnet(uri)) {
  353. try {
  354. SharedHandle<RequestGroup> group =
  355. createBtMagnetRequestGroup(uri, option_, std::vector<std::string>());
  356. requestGroups_.push_back(group);
  357. } catch(RecoverableException& e) {
  358. // error occurred while parsing torrent file.
  359. // We simply ignore it.
  360. LogFactory::getInstance()->error(EX_EXCEPTION_CAUGHT, e);
  361. }
  362. } else if(!ignoreLocalPath_ && detector_.guessTorrentFile(uri)) {
  363. try {
  364. requestGroups_.push_back
  365. (createBtRequestGroup(uri, option_, std::vector<std::string>()));
  366. } catch(RecoverableException& e) {
  367. // error occurred while parsing torrent file.
  368. // We simply ignore it.
  369. LogFactory::getInstance()->error(EX_EXCEPTION_CAUGHT, e);
  370. }
  371. }
  372. #endif // ENABLE_BITTORRENT
  373. #ifdef ENABLE_METALINK
  374. else if(!ignoreLocalPath_ && detector_.guessMetalinkFile(uri)) {
  375. try {
  376. Metalink2RequestGroup().generate(requestGroups_, uri, option_);
  377. } catch(RecoverableException& e) {
  378. // error occurred while parsing metalink file.
  379. // We simply ignore it.
  380. LogFactory::getInstance()->error(EX_EXCEPTION_CAUGHT, e);
  381. }
  382. }
  383. #endif // ENABLE_METALINK
  384. else {
  385. LogFactory::getInstance()->error(MSG_UNRECOGNIZED_URI, (uri).c_str());
  386. }
  387. }
  388. };
  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. void createRequestGroupForUri
  398. (std::vector<SharedHandle<RequestGroup> >& result,
  399. const SharedHandle<Option>& option,
  400. const std::vector<std::string>& uris,
  401. bool ignoreForceSequential,
  402. bool ignoreLocalPath)
  403. {
  404. std::vector<std::string> nargs;
  405. if(option->get(PREF_PARAMETERIZED_URI) == V_TRUE) {
  406. unfoldURI(nargs, uris);
  407. } else {
  408. nargs = uris;
  409. }
  410. if(!ignoreForceSequential && option->get(PREF_FORCE_SEQUENTIAL) == V_TRUE) {
  411. std::for_each(nargs.begin(), nargs.end(),
  412. AccRequestGroup(result, option, ignoreLocalPath));
  413. } else {
  414. std::vector<std::string>::iterator strmProtoEnd =
  415. std::stable_partition(nargs.begin(), nargs.end(), StreamProtocolFilter());
  416. // let's process http/ftp protocols first.
  417. if(nargs.begin() != strmProtoEnd) {
  418. size_t numIter = option->getAsInt(PREF_MAX_CONNECTION_PER_SERVER);
  419. size_t numSplit = option->getAsInt(PREF_SPLIT);
  420. std::vector<std::string> streamURIs;
  421. splitURI(streamURIs, nargs.begin(), strmProtoEnd, numSplit, numIter);
  422. SharedHandle<RequestGroup> rg =
  423. createRequestGroup(option, streamURIs, true);
  424. rg->setNumConcurrentCommand(numSplit);
  425. result.push_back(rg);
  426. }
  427. // process remaining URIs(local metalink, BitTorrent files)
  428. std::for_each(strmProtoEnd, nargs.end(),
  429. AccRequestGroup(result, option, ignoreLocalPath));
  430. }
  431. }
  432. static void createRequestGroupForUriList
  433. (std::vector<SharedHandle<RequestGroup> >& result,
  434. const SharedHandle<Option>& option,
  435. std::istream& in)
  436. {
  437. UriListParser p(in);
  438. while(p.hasNext()) {
  439. std::vector<std::string> uris;
  440. SharedHandle<Option> tempOption(new Option());
  441. p.parseNext(uris, *tempOption.get());
  442. if(uris.empty()) {
  443. continue;
  444. }
  445. SharedHandle<Option> requestOption(new Option(*option.get()));
  446. for(std::set<std::string>::const_iterator i =
  447. listRequestOptions().begin(), eoi = listRequestOptions().end();
  448. i != eoi; ++i) {
  449. if(tempOption->defined(*i)) {
  450. requestOption->put(*i, tempOption->get(*i));
  451. }
  452. }
  453. createRequestGroupForUri(result, requestOption, uris);
  454. }
  455. }
  456. void createRequestGroupForUriList
  457. (std::vector<SharedHandle<RequestGroup> >& result,
  458. const SharedHandle<Option>& option)
  459. {
  460. if(option->get(PREF_INPUT_FILE) == "-") {
  461. createRequestGroupForUriList(result, option, std::cin);
  462. } else {
  463. if(!File(option->get(PREF_INPUT_FILE)).isFile()) {
  464. throw DL_ABORT_EX
  465. (StringFormat(EX_FILE_OPEN, option->get(PREF_INPUT_FILE).c_str(),
  466. "No such file").str());
  467. }
  468. std::ifstream f(option->get(PREF_INPUT_FILE).c_str(), std::ios::binary);
  469. createRequestGroupForUriList(result, option, f);
  470. }
  471. }
  472. SharedHandle<MetadataInfo>
  473. createMetadataInfoFromFirstFileEntry(const SharedHandle<DownloadContext>& dctx)
  474. {
  475. if(dctx->getFileEntries().empty()) {
  476. return SharedHandle<MetadataInfo>();
  477. } else {
  478. std::vector<std::string> uris;
  479. dctx->getFileEntries()[0]->getUris(uris);
  480. if(uris.empty()) {
  481. return SharedHandle<MetadataInfo>();
  482. }
  483. return SharedHandle<MetadataInfo>(new MetadataInfo(uris[0]));
  484. }
  485. }
  486. } // namespace aria2