option_processing.cc 11 KB

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