main.cc 14 KB

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