download_helper.cc 15 KB

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