main.cc 13 KB

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