option_processing.cc 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  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 <cstdlib>
  37. #include <cstring>
  38. #include <sstream>
  39. #include <aria2/aria2.h>
  40. #include "Option.h"
  41. #include "prefs.h"
  42. #include "OptionParser.h"
  43. #include "OptionHandlerFactory.h"
  44. #include "OptionHandler.h"
  45. #include "util.h"
  46. #include "message.h"
  47. #include "Exception.h"
  48. #include "a2io.h"
  49. #include "help_tags.h"
  50. #include "File.h"
  51. #include "fmt.h"
  52. #include "OptionHandlerException.h"
  53. #include "UnknownOptionException.h"
  54. #include "error_code.h"
  55. #include "SimpleRandomizer.h"
  56. #include "bittorrent_helper.h"
  57. #include "BufferedFile.h"
  58. #include "console.h"
  59. #include "array_fun.h"
  60. #include "LogFactory.h"
  61. #ifndef HAVE_DAEMON
  62. #include "daemon.h"
  63. #endif // !HAVE_DAEMON
  64. namespace aria2 {
  65. extern void showVersion();
  66. extern void showUsage(const std::string& keyword,
  67. const std::shared_ptr<OptionParser>& oparser,
  68. const Console& out);
  69. namespace {
  70. void overrideWithEnv(Option& op,
  71. const std::shared_ptr<OptionParser>& optionParser,
  72. PrefPtr pref, const std::string& envName)
  73. {
  74. char* value = getenv(envName.c_str());
  75. if (value) {
  76. try {
  77. optionParser->find(pref)->parse(op, value);
  78. }
  79. catch (Exception& e) {
  80. global::cerr()->printf(
  81. _("Caught Error while parsing environment variable '%s'"),
  82. envName.c_str());
  83. global::cerr()->printf("\n%s\n", e.stackTrace().c_str());
  84. }
  85. }
  86. }
  87. } // namespace
  88. namespace {
  89. // Calculates Damerau–Levenshtein distance between c-string a and b
  90. // with given costs. swapcost, subcost, addcost and delcost are cost
  91. // to swap 2 adjacent characters, substitute characters, add character
  92. // and delete character respectively.
  93. int levenshtein(const char* a, const char* b, int swapcost, int subcost,
  94. int addcost, int delcost)
  95. {
  96. int alen = strlen(a);
  97. int blen = strlen(b);
  98. std::vector<std::vector<int>> dp(3, std::vector<int>(blen + 1));
  99. for (int i = 0; i <= blen; ++i) {
  100. dp[1][i] = i;
  101. }
  102. for (int i = 1; i <= alen; ++i) {
  103. dp[0][0] = i;
  104. for (int j = 1; j <= blen; ++j) {
  105. dp[0][j] = dp[1][j - 1] + (a[i - 1] == b[j - 1] ? 0 : subcost);
  106. if (i >= 2 && j >= 2 && a[i - 1] != b[j - 1] && a[i - 2] == b[j - 1] &&
  107. a[i - 1] == b[j - 2]) {
  108. dp[0][j] = std::min(dp[0][j], dp[2][j - 2] + swapcost);
  109. }
  110. dp[0][j] = std::min(dp[0][j],
  111. std::min(dp[1][j] + delcost, dp[0][j - 1] + addcost));
  112. }
  113. std::rotate(dp.begin(), dp.begin() + 2, dp.end());
  114. }
  115. return dp[1][blen];
  116. }
  117. } // namespace
  118. namespace {
  119. void showCandidates(const std::string& unknownOption,
  120. const std::shared_ptr<OptionParser>& parser)
  121. {
  122. const char* optstr = unknownOption.c_str();
  123. for (; *optstr == '-'; ++optstr)
  124. ;
  125. if (*optstr == '\0') {
  126. return;
  127. }
  128. int optstrlen = strlen(optstr);
  129. std::vector<std::pair<int, PrefPtr>> cands;
  130. for (int i = 1, len = option::countOption(); i < len; ++i) {
  131. PrefPtr pref = option::i2p(i);
  132. const OptionHandler* h = parser->find(pref);
  133. if (!h || h->isHidden()) {
  134. continue;
  135. }
  136. // Use cost 0 for prefix match
  137. if (util::startsWith(pref->k, pref->k + strlen(pref->k), optstr,
  138. optstr + optstrlen)) {
  139. cands.push_back(std::make_pair(0, pref));
  140. continue;
  141. }
  142. // cost values are borrowed from git, help.c.
  143. int sim = levenshtein(optstr, pref->k, 0, 2, 1, 4);
  144. cands.push_back(std::make_pair(sim, pref));
  145. }
  146. if (cands.empty()) {
  147. return;
  148. }
  149. std::sort(cands.begin(), cands.end());
  150. int threshold = cands[0].first;
  151. // threshold value 12 is a magic value.
  152. if (threshold > 12) {
  153. return;
  154. }
  155. global::cerr()->printf("\n");
  156. global::cerr()->printf(_("Did you mean:"));
  157. global::cerr()->printf("\n");
  158. for (auto i = cands.begin(), eoi = cands.end();
  159. i != eoi && (*i).first <= threshold; ++i) {
  160. global::cerr()->printf("\t--%s\n", (*i).second->k);
  161. }
  162. }
  163. } // namespace
  164. error_code::Value option_processing(Option& op, bool standalone,
  165. std::vector<std::string>& uris, int argc,
  166. char** argv, const KeyVals& options)
  167. {
  168. const std::shared_ptr<OptionParser>& oparser = OptionParser::getInstance();
  169. try {
  170. bool noConf = false;
  171. std::string ucfname;
  172. std::stringstream cmdstream;
  173. {
  174. // first evaluate --no-conf and --conf-path options.
  175. Option op;
  176. if (argc == 0) {
  177. oparser->parse(op, options);
  178. }
  179. else {
  180. oparser->parseArg(cmdstream, uris, argc, argv);
  181. oparser->parse(op, cmdstream);
  182. }
  183. noConf = op.getAsBool(PREF_NO_CONF);
  184. ucfname = op.get(PREF_CONF_PATH);
  185. if (standalone) {
  186. if (op.defined(PREF_VERSION)) {
  187. showVersion();
  188. exit(error_code::FINISHED);
  189. }
  190. if (op.defined(PREF_HELP)) {
  191. std::string keyword;
  192. if (op.get(PREF_HELP).empty()) {
  193. keyword = strHelpTag(TAG_BASIC);
  194. }
  195. else {
  196. keyword = op.get(PREF_HELP);
  197. if (util::startsWith(keyword, "--")) {
  198. keyword.erase(keyword.begin(), keyword.begin() + 2);
  199. }
  200. std::string::size_type eqpos = keyword.find("=");
  201. if (eqpos != std::string::npos) {
  202. keyword.erase(keyword.begin() + eqpos, keyword.end());
  203. }
  204. }
  205. showUsage(keyword, oparser, global::cout());
  206. exit(error_code::FINISHED);
  207. }
  208. }
  209. }
  210. auto confOption = std::make_shared<Option>();
  211. oparser->parseDefaultValues(*confOption);
  212. if (!noConf) {
  213. std::string cfname =
  214. ucfname.empty() ? oparser->find(PREF_CONF_PATH)->getDefaultValue()
  215. : ucfname;
  216. if (File(cfname).isFile()) {
  217. std::stringstream ss;
  218. {
  219. BufferedFile fp(cfname.c_str(), BufferedFile::READ);
  220. if (fp) {
  221. fp.transfer(ss);
  222. }
  223. }
  224. try {
  225. oparser->parse(*confOption, ss);
  226. }
  227. catch (OptionHandlerException& e) {
  228. global::cerr()->printf(_("Parse error in %s"), cfname.c_str());
  229. global::cerr()->printf("\n%s", e.stackTrace().c_str());
  230. const OptionHandler* h = oparser->find(e.getPref());
  231. if (h) {
  232. global::cerr()->printf(_("Usage:"));
  233. global::cerr()->printf("\n%s\n", h->getDescription());
  234. }
  235. return e.getErrorCode();
  236. }
  237. catch (Exception& e) {
  238. global::cerr()->printf(_("Parse error in %s"), cfname.c_str());
  239. global::cerr()->printf("\n%s", e.stackTrace().c_str());
  240. return e.getErrorCode();
  241. }
  242. }
  243. else if (!ucfname.empty()) {
  244. global::cerr()->printf(_("Configuration file %s is not found."),
  245. cfname.c_str());
  246. global::cerr()->printf("\n");
  247. showUsage(strHelpTag(TAG_HELP), oparser, global::cerr());
  248. return error_code::UNKNOWN_ERROR;
  249. }
  250. }
  251. // Override configuration with environment variables.
  252. overrideWithEnv(*confOption, oparser, PREF_HTTP_PROXY, "http_proxy");
  253. overrideWithEnv(*confOption, oparser, PREF_HTTPS_PROXY, "https_proxy");
  254. overrideWithEnv(*confOption, oparser, PREF_FTP_PROXY, "ftp_proxy");
  255. overrideWithEnv(*confOption, oparser, PREF_ALL_PROXY, "all_proxy");
  256. overrideWithEnv(*confOption, oparser, PREF_NO_PROXY, "no_proxy");
  257. if (!standalone) {
  258. // For non-standalone mode, set PREF_QUIET to true to suppress
  259. // output. The caller can override this by including PREF_QUIET
  260. // in options argument.
  261. confOption->put(PREF_QUIET, A2_V_TRUE);
  262. }
  263. // we must clear eof bit and seek to the beginning of the buffer.
  264. cmdstream.clear();
  265. cmdstream.seekg(0, std::ios::beg);
  266. // finaly let's parse and store command-iine options.
  267. op.setParent(confOption);
  268. oparser->parse(op, cmdstream);
  269. oparser->parse(op, options);
  270. }
  271. catch (OptionHandlerException& e) {
  272. global::cerr()->printf("%s", e.stackTrace().c_str());
  273. const OptionHandler* h = oparser->find(e.getPref());
  274. if (h) {
  275. global::cerr()->printf(_("Usage:"));
  276. global::cerr()->printf("\n");
  277. write(global::cerr(), *h);
  278. }
  279. return e.getErrorCode();
  280. }
  281. catch (UnknownOptionException& e) {
  282. showUsage("", oparser, global::cerr());
  283. showCandidates(e.getUnknownOption(), oparser);
  284. return e.getErrorCode();
  285. }
  286. catch (Exception& e) {
  287. global::cerr()->printf("%s", e.stackTrace().c_str());
  288. showUsage("", oparser, global::cerr());
  289. return e.getErrorCode();
  290. }
  291. if (standalone && op.getAsBool(PREF_STDERR)) {
  292. global::redirectStdoutToStderr();
  293. }
  294. if (standalone && !op.getAsBool(PREF_ENABLE_RPC) &&
  295. #ifdef ENABLE_BITTORRENT
  296. op.blank(PREF_TORRENT_FILE) &&
  297. #endif // ENABLE_BITTORRENT
  298. #ifdef ENABLE_METALINK
  299. op.blank(PREF_METALINK_FILE) &&
  300. #endif // ENABLE_METALINK
  301. op.blank(PREF_INPUT_FILE)) {
  302. if (uris.empty()) {
  303. global::cerr()->printf(MSG_URI_REQUIRED);
  304. global::cerr()->printf("\n");
  305. showUsage("", oparser, global::cerr());
  306. return error_code::UNKNOWN_ERROR;
  307. }
  308. }
  309. if (standalone && op.getAsBool(PREF_DAEMON)) {
  310. #if defined(__GNUC__) && defined(__APPLE__)
  311. // daemon() is deprecated on OSX since... forever.
  312. // Silence the warning for good, so that -Werror becomes feasible.
  313. #pragma GCC diagnostic push
  314. #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
  315. #endif // defined(__GNUC__) && defined(__APPLE__)
  316. const auto daemonized = daemon(0, 0);
  317. #if defined(__GNUC__) && defined(__APPLE__)
  318. #pragma GCC diagnostic pop
  319. #endif // defined(__GNUC__) && defined(__APPLE__)
  320. if (daemonized < 0) {
  321. perror(MSG_DAEMON_FAILED);
  322. return error_code::UNKNOWN_ERROR;
  323. }
  324. }
  325. if (op.getAsBool(PREF_DEFERRED_INPUT) && op.defined(PREF_SAVE_SESSION)) {
  326. A2_LOG_WARN("--deferred-input is disabled because of the presence of "
  327. "--save-session");
  328. op.remove(PREF_DEFERRED_INPUT);
  329. }
  330. return error_code::FINISHED;
  331. }
  332. } // namespace aria2