main.cc 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462
  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;
  180. Metalink2RequestGroup(op).generate(groups, op->get(PREF_METALINK_FILE));
  181. if(groups.empty()) {
  182. throw FatalException("No files to download.");
  183. }
  184. return MultiUrlRequestInfo(groups, op, getStatCalc(op), getSummaryOut(op)).execute();
  185. }
  186. #endif // ENABLE_METALINK
  187. class AccRequestGroup {
  188. private:
  189. std::deque<SharedHandle<RequestGroup> >& _requestGroups;
  190. ProtocolDetector _detector;
  191. Option* _op;
  192. public:
  193. AccRequestGroup(std::deque<SharedHandle<RequestGroup> >& requestGroups,
  194. Option* op):
  195. _requestGroups(requestGroups), _op(op) {}
  196. void
  197. operator()(const std::string& uri)
  198. {
  199. if(_detector.isStreamProtocol(uri)) {
  200. std::deque<std::string> xuris;
  201. for(size_t count = _op->getAsInt(PREF_SPLIT); count; --count) {
  202. xuris.push_back(uri);
  203. }
  204. RequestGroupHandle rg = createRequestGroup(_op, xuris);
  205. _requestGroups.push_back(rg);
  206. }
  207. #ifdef ENABLE_BITTORRENT
  208. else if(_detector.guessTorrentFile(uri)) {
  209. try {
  210. _requestGroups.push_back(createBtRequestGroup(uri, _op,
  211. std::deque<std::string>()));
  212. } catch(RecoverableException& e) {
  213. // error occurred while parsing torrent file.
  214. // We simply ignore it.
  215. LogFactory::getInstance()->error(EX_EXCEPTION_CAUGHT, e);
  216. }
  217. }
  218. #endif // ENABLE_BITTORRENT
  219. #ifdef ENABLE_METALINK
  220. else if(_detector.guessMetalinkFile(uri)) {
  221. try {
  222. Metalink2RequestGroup(_op).generate(_requestGroups, uri);
  223. } catch(RecoverableException& e) {
  224. // error occurred while parsing metalink file.
  225. // We simply ignore it.
  226. LogFactory::getInstance()->error(EX_EXCEPTION_CAUGHT, e);
  227. }
  228. }
  229. #endif // ENABLE_METALINK
  230. else {
  231. LogFactory::getInstance()->error(MSG_UNRECOGNIZED_URI, (uri).c_str());
  232. }
  233. }
  234. };
  235. int32_t downloadUriList(Option* op, std::istream& in)
  236. {
  237. UriListParser p;
  238. RequestGroups groups;
  239. while(in) {
  240. std::deque<std::string> uris = p.parseNext(in);
  241. if(uris.size() == 1 && op->get(PREF_PARAMETERIZED_URI) == V_TRUE) {
  242. std::deque<std::string> unfoldedURIs = unfoldURI(uris);
  243. std::for_each(unfoldedURIs.begin(), unfoldedURIs.end(),
  244. AccRequestGroup(groups, op));
  245. } else if(uris.size() == 1) {
  246. std::for_each(uris.begin(), uris.end(), AccRequestGroup(groups, op));
  247. } else if(uris.size() > 0) {
  248. std::deque<std::string> xuris;
  249. ncopy(uris.begin(), uris.end(), op->getAsInt(PREF_SPLIT),
  250. std::back_inserter(xuris));
  251. SharedHandle<RequestGroup> rg = createRequestGroup(op, xuris);
  252. groups.push_back(rg);
  253. }
  254. }
  255. return MultiUrlRequestInfo(groups, op, getStatCalc(op), getSummaryOut(op)).execute();
  256. }
  257. int32_t downloadUriList(Option* op)
  258. {
  259. if(op->get(PREF_INPUT_FILE) == "-") {
  260. return downloadUriList(op, std::cin);
  261. } else {
  262. if(!File(op->get(PREF_INPUT_FILE)).isFile()) {
  263. throw FatalException
  264. (StringFormat(EX_FILE_OPEN, op->get(PREF_INPUT_FILE).c_str(),
  265. "No such file").str());
  266. }
  267. std::ifstream f(op->get(PREF_INPUT_FILE).c_str());
  268. return downloadUriList(op, f);
  269. }
  270. }
  271. class StreamProtocolFilter {
  272. private:
  273. ProtocolDetector _detector;
  274. public:
  275. bool operator()(const std::string& uri) {
  276. return _detector.isStreamProtocol(uri);
  277. }
  278. };
  279. int32_t downloadUri(Option* op, const std::deque<std::string>& uris)
  280. {
  281. std::deque<std::string> nargs;
  282. if(op->get(PREF_PARAMETERIZED_URI) == V_TRUE) {
  283. nargs = unfoldURI(uris);
  284. } else {
  285. nargs = uris;
  286. }
  287. RequestGroups groups;
  288. if(op->get(PREF_FORCE_SEQUENTIAL) == V_TRUE) {
  289. std::for_each(nargs.begin(), nargs.end(), AccRequestGroup(groups, op));
  290. } else {
  291. std::deque<std::string>::iterator strmProtoEnd =
  292. std::stable_partition(nargs.begin(), nargs.end(), StreamProtocolFilter());
  293. // let's process http/ftp protocols first.
  294. std::deque<std::string> xargs;
  295. ncopy(nargs.begin(), strmProtoEnd, op->getAsInt(PREF_SPLIT),
  296. std::back_inserter(xargs));
  297. if(xargs.size()) {
  298. RequestGroupHandle rg = createRequestGroup(op, xargs, op->get(PREF_OUT));
  299. groups.push_back(rg);
  300. }
  301. // process remaining URIs(local metalink, BitTorrent files)
  302. std::for_each(strmProtoEnd, nargs.end(), AccRequestGroup(groups, op));
  303. }
  304. return MultiUrlRequestInfo(groups, op, getStatCalc(op), getSummaryOut(op)).execute();
  305. }
  306. int main(int argc, char* argv[])
  307. {
  308. Option* op = option_processing(argc, argv);
  309. std::deque<std::string> args(argv+optind, argv+argc);
  310. SimpleRandomizer::init();
  311. BitfieldManFactory::setDefaultRandomizer(SimpleRandomizer::getInstance());
  312. if(op->getAsBool(PREF_STDOUT_LOG)) {
  313. LogFactory::setLogFile(DEV_STDOUT);
  314. } else if(op->get(PREF_LOG).size()) {
  315. LogFactory::setLogFile(op->get(PREF_LOG));
  316. } else {
  317. LogFactory::setLogFile(DEV_NULL);
  318. }
  319. if(op->getAsBool(PREF_QUIET)) {
  320. LogFactory::setConsoleOutput(false);
  321. }
  322. int32_t exitStatus = EXIT_SUCCESS;
  323. try {
  324. Logger* logger = LogFactory::getInstance();
  325. logger->info("%s %s %s", PACKAGE, PACKAGE_VERSION, TARGET);
  326. logger->info(MSG_LOGGING_STARTED);
  327. AuthConfigFactoryHandle authConfigFactory(new AuthConfigFactory(op));
  328. File netrccf(op->get(PREF_NETRC_PATH));
  329. if(!op->getAsBool(PREF_NO_NETRC) && netrccf.isFile()) {
  330. mode_t mode = netrccf.mode();
  331. if(mode&(S_IRWXG|S_IRWXO)) {
  332. logger->notice(MSG_INCORRECT_NETRC_PERMISSION,
  333. op->get(PREF_NETRC_PATH).c_str());
  334. } else {
  335. NetrcHandle netrc(new Netrc());
  336. netrc->parse(op->get(PREF_NETRC_PATH));
  337. authConfigFactory->setNetrc(netrc);
  338. }
  339. }
  340. CookieBoxFactoryHandle cookieBoxFactory(new CookieBoxFactory());
  341. CookieBoxFactorySingletonHolder::instance(cookieBoxFactory);
  342. if(op->defined(PREF_LOAD_COOKIES)) {
  343. File cookieFile(op->get(PREF_LOAD_COOKIES));
  344. if(cookieFile.isFile()) {
  345. std::ifstream in(op->get(PREF_LOAD_COOKIES).c_str());
  346. CookieBoxFactorySingletonHolder::instance()->loadDefaultCookie(in);
  347. } else {
  348. logger->error(MSG_LOADING_COOKIE_FAILED, op->get(PREF_LOAD_COOKIES).c_str());
  349. exit(EXIT_FAILURE);
  350. }
  351. }
  352. AuthConfigFactorySingleton::instance(authConfigFactory);
  353. CUIDCounterHandle cuidCounter(new CUIDCounter());
  354. CUIDCounterSingletonHolder::instance(cuidCounter);
  355. #ifdef ENABLE_MESSAGE_DIGEST
  356. MessageDigestHelper::staticSHA1DigestInit();
  357. #endif // ENABLE_MESSAGE_DIGEST
  358. #ifdef SIGPIPE
  359. Util::setGlobalSignalHandler(SIGPIPE, SIG_IGN, 0);
  360. #endif
  361. int32_t returnValue = 0;
  362. #ifdef ENABLE_BITTORRENT
  363. if(op->defined(PREF_TORRENT_FILE)) {
  364. if(op->get(PREF_SHOW_FILES) == V_TRUE) {
  365. DefaultBtContextHandle btContext(new DefaultBtContext());
  366. btContext->load(op->get(PREF_TORRENT_FILE));
  367. std::cout << btContext << std::endl;
  368. } else {
  369. returnValue = downloadBitTorrent(op, args);
  370. }
  371. }
  372. else
  373. #endif // ENABLE_BITTORRENT
  374. #ifdef ENABLE_METALINK
  375. if(op->defined(PREF_METALINK_FILE)) {
  376. if(op->get(PREF_SHOW_FILES) == V_TRUE) {
  377. std::deque<SharedHandle<MetalinkEntry> > metalinkEntries;
  378. MetalinkHelper::parseAndQuery(metalinkEntries,
  379. op->get(PREF_METALINK_FILE), op);
  380. std::deque<SharedHandle<FileEntry> > fileEntries;
  381. MetalinkEntry::toFileEntry(fileEntries, metalinkEntries);
  382. Util::toStream(std::cout, fileEntries);
  383. } else {
  384. returnValue = downloadMetalink(op);
  385. }
  386. }
  387. else
  388. #endif // ENABLE_METALINK
  389. if(op->defined(PREF_INPUT_FILE)) {
  390. returnValue = downloadUriList(op);
  391. } else {
  392. returnValue = downloadUri(op, args);
  393. }
  394. if(returnValue == 1) {
  395. exitStatus = EXIT_FAILURE;
  396. }
  397. } catch(Exception& ex) {
  398. std::cerr << EX_EXCEPTION_CAUGHT << "\n" << ex.stackTrace() << std::endl;
  399. exitStatus = EXIT_FAILURE;
  400. }
  401. delete op;
  402. LogFactory::release();
  403. return exitStatus;
  404. }
  405. } // namespace aria2
  406. int main(int argc, char* argv[]) {
  407. #ifdef HAVE_WINSOCK2_H
  408. aria2::Platform platform;
  409. #endif // HAVE_WINSOCK2_H
  410. #ifdef ENABLE_NLS
  411. setlocale (LC_CTYPE, "");
  412. setlocale (LC_MESSAGES, "");
  413. bindtextdomain (PACKAGE, LOCALEDIR);
  414. textdomain (PACKAGE);
  415. #endif // ENABLE_NLS
  416. #ifdef HAVE_LIBSSL
  417. // for SSL initialization
  418. SSL_load_error_strings();
  419. SSL_library_init();
  420. #endif // HAVE_LIBSSL
  421. #ifdef HAVE_LIBGNUTLS
  422. gnutls_global_init();
  423. #endif // HAVE_LIBGNUTLS
  424. int r = aria2::main(argc, argv);
  425. #ifdef HAVE_LIBGNUTLS
  426. gnutls_global_deinit();
  427. #endif // HAVE_LIBGNUTLS
  428. return r;
  429. }