main.cc 14 KB

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