download_helper.cc 15 KB

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