download_helper.cc 14 KB

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