download_helper.cc 12 KB

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