main.cc 14 KB

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