main.cc 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452
  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 "common.h"
  36. #include <signal.h>
  37. #include <unistd.h>
  38. #include <getopt.h>
  39. #include <deque>
  40. #include <fstream>
  41. #include <iostream>
  42. #include <numeric>
  43. #include "SharedHandle.h"
  44. #include "LogFactory.h"
  45. #include "Logger.h"
  46. #include "Util.h"
  47. #include "BitfieldManFactory.h"
  48. #include "FeatureConfig.h"
  49. #include "MultiUrlRequestInfo.h"
  50. #include "SimpleRandomizer.h"
  51. #include "FatalException.h"
  52. #include "File.h"
  53. #include "UriListParser.h"
  54. #include "message.h"
  55. #include "prefs.h"
  56. #include "Option.h"
  57. #include "a2algo.h"
  58. #include "a2io.h"
  59. #include "a2time.h"
  60. #include "Platform.h"
  61. #include "ParameterizedStringParser.h"
  62. #include "PStringBuildVisitor.h"
  63. #include "SingleFileDownloadContext.h"
  64. #include "DefaultBtContext.h"
  65. #include "FileEntry.h"
  66. #include "RequestGroup.h"
  67. #include "ProtocolDetector.h"
  68. #include "ConsoleStatCalc.h"
  69. #include "NullStatCalc.h"
  70. #include "StringFormat.h"
  71. #include "A2STR.h"
  72. #include "RecoverableException.h"
  73. #ifdef ENABLE_METALINK
  74. # include "MetalinkHelper.h"
  75. # include "Metalink2RequestGroup.h"
  76. # include "MetalinkEntry.h"
  77. #endif // ENABLE_METALINK
  78. #ifdef ENABLE_MESSAGE_DIGEST
  79. # include "MessageDigestHelper.h"
  80. #endif // ENABLE_MESSAGE_DIGEST
  81. extern char* optarg;
  82. extern int optind, opterr, optopt;
  83. namespace aria2 {
  84. // output stream to /dev/null
  85. std::ofstream nullout(DEV_NULL);
  86. std::deque<std::string> unfoldURI(const std::deque<std::string>& args)
  87. {
  88. std::deque<std::string> nargs;
  89. ParameterizedStringParser p;
  90. PStringBuildVisitor v;
  91. for(std::deque<std::string>::const_iterator itr = args.begin(); itr != args.end();
  92. ++itr) {
  93. v.reset();
  94. p.parse(*itr)->accept(&v);
  95. nargs.insert(nargs.end(), v.getURIs().begin(), v.getURIs().end());
  96. }
  97. return nargs;
  98. }
  99. RequestGroupHandle createRequestGroup
  100. (const Option* op, const std::deque<std::string>& uris,
  101. const Option& requestOption)
  102. {
  103. RequestGroupHandle rg(new RequestGroup(op, uris));
  104. SingleFileDownloadContextHandle dctx
  105. (new SingleFileDownloadContext(op->getAsInt(PREF_SEGMENT_SIZE),
  106. 0,
  107. A2STR::NIL,
  108. requestOption.get(PREF_OUT)));
  109. dctx->setDir(requestOption.get(PREF_DIR));
  110. rg->setDownloadContext(dctx);
  111. return rg;
  112. }
  113. SharedHandle<StatCalc> getStatCalc(const Option* op)
  114. {
  115. SharedHandle<StatCalc> statCalc;
  116. if(op->getAsBool(PREF_QUIET)) {
  117. statCalc.reset(new NullStatCalc());
  118. } else {
  119. statCalc.reset(new ConsoleStatCalc(op->getAsInt(PREF_SUMMARY_INTERVAL)));
  120. }
  121. return statCalc;
  122. }
  123. std::ostream& getSummaryOut(const Option* op)
  124. {
  125. if(op->getAsBool(PREF_QUIET)) {
  126. return nullout;
  127. } else {
  128. return std::cout;
  129. }
  130. }
  131. extern Option* option_processing(int argc, char* const argv[]);
  132. #ifdef ENABLE_BITTORRENT
  133. SharedHandle<RequestGroup>
  134. createBtRequestGroup(const std::string& torrentFilePath,
  135. Option* op,
  136. const std::deque<std::string>& auxUris,
  137. const Option& requestOption)
  138. {
  139. SharedHandle<RequestGroup> rg(new RequestGroup(op, auxUris));
  140. SharedHandle<DefaultBtContext> btContext(new DefaultBtContext());
  141. btContext->load(torrentFilePath);// may throw exception
  142. if(op->defined(PREF_PEER_ID_PREFIX)) {
  143. btContext->setPeerIdPrefix(op->get(PREF_PEER_ID_PREFIX));
  144. }
  145. btContext->setDir(requestOption.get(PREF_DIR));
  146. rg->setDownloadContext(btContext);
  147. btContext->setOwnerRequestGroup(rg.get());
  148. return rg;
  149. }
  150. int32_t downloadBitTorrent(Option* op, const std::deque<std::string>& uris)
  151. {
  152. std::deque<std::string> nargs;
  153. if(op->get(PREF_PARAMETERIZED_URI) == V_TRUE) {
  154. nargs = unfoldURI(uris);
  155. } else {
  156. nargs = uris;
  157. }
  158. RequestGroups groups;
  159. size_t numSplit = op->getAsInt(PREF_SPLIT);
  160. if(nargs.size() >= numSplit) {
  161. RequestGroupHandle rg = createBtRequestGroup(op->get(PREF_TORRENT_FILE),
  162. op, nargs, *op);
  163. rg->setNumConcurrentCommand(numSplit);
  164. groups.push_back(rg);
  165. } else {
  166. std::deque<std::string> xargs;
  167. if(!nargs.empty()) {
  168. ncopy(nargs.begin(), nargs.end(), numSplit, std::back_inserter(xargs));
  169. xargs.erase(xargs.begin()+numSplit, xargs.end());
  170. }
  171. RequestGroupHandle rg = createBtRequestGroup(op->get(PREF_TORRENT_FILE),
  172. op, xargs, *op);
  173. rg->setNumConcurrentCommand(numSplit);
  174. groups.push_back(rg);
  175. }
  176. return MultiUrlRequestInfo(groups, op, getStatCalc(op), getSummaryOut(op)).execute();
  177. }
  178. #endif // ENABLE_BITTORRENT
  179. #ifdef ENABLE_METALINK
  180. int32_t downloadMetalink(Option* op)
  181. {
  182. RequestGroups groups;
  183. Metalink2RequestGroup(op).generate(groups, op->get(PREF_METALINK_FILE), *op);
  184. if(groups.empty()) {
  185. throw FatalException("No files to download.");
  186. }
  187. return MultiUrlRequestInfo(groups, op, getStatCalc(op), getSummaryOut(op)).execute();
  188. }
  189. #endif // ENABLE_METALINK
  190. class AccRequestGroup {
  191. private:
  192. std::deque<SharedHandle<RequestGroup> >& _requestGroups;
  193. ProtocolDetector _detector;
  194. Option* _op;
  195. Option& _requestOption;
  196. public:
  197. AccRequestGroup(std::deque<SharedHandle<RequestGroup> >& requestGroups,
  198. Option* op,
  199. Option& requestOption):
  200. _requestGroups(requestGroups), _op(op), _requestOption(requestOption) {}
  201. void
  202. operator()(const std::string& uri)
  203. {
  204. if(_detector.isStreamProtocol(uri)) {
  205. std::deque<std::string> xuris;
  206. for(size_t count = _op->getAsInt(PREF_SPLIT); count; --count) {
  207. xuris.push_back(uri);
  208. }
  209. RequestGroupHandle rg = createRequestGroup(_op, xuris, _requestOption);
  210. _requestGroups.push_back(rg);
  211. }
  212. #ifdef ENABLE_BITTORRENT
  213. else if(_detector.guessTorrentFile(uri)) {
  214. try {
  215. _requestGroups.push_back(createBtRequestGroup(uri, _op,
  216. std::deque<std::string>(),
  217. _requestOption));
  218. } catch(RecoverableException& e) {
  219. // error occurred while parsing torrent file.
  220. // We simply ignore it.
  221. LogFactory::getInstance()->error(EX_EXCEPTION_CAUGHT, e);
  222. }
  223. }
  224. #endif // ENABLE_BITTORRENT
  225. #ifdef ENABLE_METALINK
  226. else if(_detector.guessMetalinkFile(uri)) {
  227. try {
  228. Metalink2RequestGroup(_op).generate(_requestGroups, uri,
  229. _requestOption);
  230. } catch(RecoverableException& e) {
  231. // error occurred while parsing metalink file.
  232. // We simply ignore it.
  233. LogFactory::getInstance()->error(EX_EXCEPTION_CAUGHT, e);
  234. }
  235. }
  236. #endif // ENABLE_METALINK
  237. else {
  238. LogFactory::getInstance()->error(MSG_UNRECOGNIZED_URI, (uri).c_str());
  239. }
  240. }
  241. };
  242. void copyIfndef(Option& dest, const Option& src, const std::string& name)
  243. {
  244. if(!dest.defined(name)) {
  245. dest.put(name, src.get(name));
  246. }
  247. }
  248. int32_t downloadUriList(Option* op, std::istream& in)
  249. {
  250. UriListParser p(in);
  251. RequestGroups groups;
  252. while(p.hasNext()) {
  253. std::deque<std::string> uris;
  254. Option requestOption;
  255. p.parseNext(uris, requestOption);
  256. copyIfndef(requestOption, *op, PREF_DIR);
  257. copyIfndef(requestOption, *op, PREF_OUT);
  258. if(uris.size() == 1 && op->get(PREF_PARAMETERIZED_URI) == V_TRUE) {
  259. std::deque<std::string> unfoldedURIs = unfoldURI(uris);
  260. std::for_each(unfoldedURIs.begin(), unfoldedURIs.end(),
  261. AccRequestGroup(groups, op, requestOption));
  262. } else if(uris.size() == 1) {
  263. std::for_each(uris.begin(), uris.end(),
  264. AccRequestGroup(groups, op, requestOption));
  265. } else if(!uris.empty()) {
  266. size_t numSplit = op->getAsInt(PREF_SPLIT);
  267. if(uris.size() >= numSplit) {
  268. SharedHandle<RequestGroup> rg =
  269. createRequestGroup(op, uris, requestOption);
  270. rg->setNumConcurrentCommand(numSplit);
  271. groups.push_back(rg);
  272. } else {
  273. std::deque<std::string> xuris;
  274. ncopy(uris.begin(), uris.end(), numSplit, std::back_inserter(xuris));
  275. xuris.erase(xuris.begin()+numSplit, xuris.end());
  276. SharedHandle<RequestGroup> rg =
  277. createRequestGroup(op, xuris, requestOption);
  278. rg->setNumConcurrentCommand(numSplit);
  279. groups.push_back(rg);
  280. }
  281. }
  282. }
  283. return MultiUrlRequestInfo(groups, op, getStatCalc(op), getSummaryOut(op)).execute();
  284. }
  285. int32_t downloadUriList(Option* op)
  286. {
  287. if(op->get(PREF_INPUT_FILE) == "-") {
  288. return downloadUriList(op, std::cin);
  289. } else {
  290. if(!File(op->get(PREF_INPUT_FILE)).isFile()) {
  291. throw FatalException
  292. (StringFormat(EX_FILE_OPEN, op->get(PREF_INPUT_FILE).c_str(),
  293. "No such file").str());
  294. }
  295. std::ifstream f(op->get(PREF_INPUT_FILE).c_str());
  296. return downloadUriList(op, f);
  297. }
  298. }
  299. class StreamProtocolFilter {
  300. private:
  301. ProtocolDetector _detector;
  302. public:
  303. bool operator()(const std::string& uri) {
  304. return _detector.isStreamProtocol(uri);
  305. }
  306. };
  307. int32_t downloadUri(Option* op, const std::deque<std::string>& uris)
  308. {
  309. std::deque<std::string> nargs;
  310. if(op->get(PREF_PARAMETERIZED_URI) == V_TRUE) {
  311. nargs = unfoldURI(uris);
  312. } else {
  313. nargs = uris;
  314. }
  315. RequestGroups groups;
  316. if(op->get(PREF_FORCE_SEQUENTIAL) == V_TRUE) {
  317. std::for_each(nargs.begin(), nargs.end(), AccRequestGroup(groups, op, *op));
  318. } else {
  319. std::deque<std::string>::iterator strmProtoEnd =
  320. std::stable_partition(nargs.begin(), nargs.end(), StreamProtocolFilter());
  321. // let's process http/ftp protocols first.
  322. size_t numSplit = op->getAsInt(PREF_SPLIT);
  323. size_t numURIs = std::distance(nargs.begin(), strmProtoEnd);
  324. if(numURIs >= numSplit) {
  325. std::deque<std::string> xargs(nargs.begin(), strmProtoEnd);
  326. RequestGroupHandle rg = createRequestGroup(op, xargs, *op);
  327. rg->setNumConcurrentCommand(numSplit);
  328. groups.push_back(rg);
  329. } else if(numURIs > 0) {
  330. std::deque<std::string> xargs;
  331. ncopy(nargs.begin(), strmProtoEnd, numSplit, std::back_inserter(xargs));
  332. xargs.erase(xargs.begin()+numSplit, xargs.end());
  333. RequestGroupHandle rg = createRequestGroup(op, xargs, *op);
  334. rg->setNumConcurrentCommand(numSplit);
  335. groups.push_back(rg);
  336. }
  337. // process remaining URIs(local metalink, BitTorrent files)
  338. std::for_each(strmProtoEnd, nargs.end(), AccRequestGroup(groups, op, *op));
  339. }
  340. return MultiUrlRequestInfo(groups, op, getStatCalc(op), getSummaryOut(op)).execute();
  341. }
  342. int main(int argc, char* argv[])
  343. {
  344. Option* op = option_processing(argc, argv);
  345. std::deque<std::string> args(argv+optind, argv+argc);
  346. SimpleRandomizer::init();
  347. BitfieldManFactory::setDefaultRandomizer(SimpleRandomizer::getInstance());
  348. if(op->get(PREF_LOG) == "-") {
  349. LogFactory::setLogFile(DEV_STDOUT);
  350. } else if(!op->get(PREF_LOG).empty()) {
  351. LogFactory::setLogFile(op->get(PREF_LOG));
  352. } else {
  353. LogFactory::setLogFile(DEV_NULL);
  354. }
  355. LogFactory::setLogLevel(op->get(PREF_LOG_LEVEL));
  356. if(op->getAsBool(PREF_QUIET)) {
  357. LogFactory::setConsoleOutput(false);
  358. }
  359. int32_t exitStatus = EXIT_SUCCESS;
  360. try {
  361. Logger* logger = LogFactory::getInstance();
  362. logger->info("<<--- --- --- ---");
  363. logger->info(" --- --- --- ---");
  364. logger->info(" --- --- --- --->>");
  365. logger->info("%s %s %s", PACKAGE, PACKAGE_VERSION, TARGET);
  366. logger->info(MSG_LOGGING_STARTED);
  367. #ifdef ENABLE_MESSAGE_DIGEST
  368. MessageDigestHelper::staticSHA1DigestInit();
  369. #endif // ENABLE_MESSAGE_DIGEST
  370. #ifdef SIGPIPE
  371. Util::setGlobalSignalHandler(SIGPIPE, SIG_IGN, 0);
  372. #endif
  373. int32_t returnValue = 0;
  374. #ifdef ENABLE_BITTORRENT
  375. if(op->defined(PREF_TORRENT_FILE)) {
  376. if(op->get(PREF_SHOW_FILES) == V_TRUE) {
  377. DefaultBtContextHandle btContext(new DefaultBtContext());
  378. btContext->load(op->get(PREF_TORRENT_FILE));
  379. std::cout << btContext << std::endl;
  380. } else {
  381. returnValue = downloadBitTorrent(op, args);
  382. }
  383. }
  384. else
  385. #endif // ENABLE_BITTORRENT
  386. #ifdef ENABLE_METALINK
  387. if(op->defined(PREF_METALINK_FILE)) {
  388. if(op->get(PREF_SHOW_FILES) == V_TRUE) {
  389. std::deque<SharedHandle<MetalinkEntry> > metalinkEntries;
  390. MetalinkHelper::parseAndQuery(metalinkEntries,
  391. op->get(PREF_METALINK_FILE), op);
  392. std::deque<SharedHandle<FileEntry> > fileEntries;
  393. MetalinkEntry::toFileEntry(fileEntries, metalinkEntries);
  394. Util::toStream(std::cout, fileEntries);
  395. } else {
  396. returnValue = downloadMetalink(op);
  397. }
  398. }
  399. else
  400. #endif // ENABLE_METALINK
  401. if(op->defined(PREF_INPUT_FILE)) {
  402. returnValue = downloadUriList(op);
  403. } else {
  404. returnValue = downloadUri(op, args);
  405. }
  406. if(returnValue == 1) {
  407. exitStatus = EXIT_FAILURE;
  408. }
  409. } catch(Exception& ex) {
  410. std::cerr << EX_EXCEPTION_CAUGHT << "\n" << ex.stackTrace() << std::endl;
  411. exitStatus = EXIT_FAILURE;
  412. }
  413. delete op;
  414. LogFactory::release();
  415. return exitStatus;
  416. }
  417. } // namespace aria2
  418. int main(int argc, char* argv[]) {
  419. aria2::Platform platform;
  420. int r = aria2::main(argc, argv);
  421. return r;
  422. }