main.cc 14 KB

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