main.cc 13 KB

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