OptionParser.cc 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  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 "OptionParser.h"
  36. #include <unistd.h>
  37. #include <getopt.h>
  38. #include <cstring>
  39. #include <cassert>
  40. #include <istream>
  41. #include <utility>
  42. #include "util.h"
  43. #include "OptionHandlerImpl.h"
  44. #include "Option.h"
  45. #include "A2STR.h"
  46. #include "a2functional.h"
  47. #include "array_fun.h"
  48. #include "OptionHandlerFactory.h"
  49. #include "DlAbortEx.h"
  50. #include "error_code.h"
  51. #include "UnknownOptionException.h"
  52. #include "LogFactory.h"
  53. #include "fmt.h"
  54. namespace aria2 {
  55. OptionParser::OptionParser()
  56. : handlers_(option::countOption(), nullptr), shortOpts_(256)
  57. {
  58. }
  59. OptionParser::~OptionParser()
  60. {
  61. std::for_each(handlers_.begin(), handlers_.end(), Deleter());
  62. }
  63. namespace {
  64. template <typename InputIterator>
  65. size_t countPublicOption(InputIterator first, InputIterator last)
  66. {
  67. size_t count = 0;
  68. for (; first != last; ++first) {
  69. if (*first && !(*first)->isHidden()) {
  70. ++count;
  71. }
  72. }
  73. return count;
  74. }
  75. } // namespace
  76. namespace {
  77. template <typename InputIterator>
  78. void putOptions(struct option* longOpts, int* plopt, InputIterator first,
  79. InputIterator last)
  80. {
  81. for (; first != last; ++first) {
  82. if (*first && !(*first)->isHidden()) {
  83. #ifdef HAVE_OPTION_CONST_NAME
  84. (*longOpts).name = (*first)->getName();
  85. #else // !HAVE_OPTION_CONST_NAME
  86. (*longOpts).name = strdup((*first)->getName());
  87. #endif // !HAVE_OPTION_CONST_NAME
  88. switch ((*first)->getArgType()) {
  89. case OptionHandler::REQ_ARG:
  90. (*longOpts).has_arg = required_argument;
  91. break;
  92. case OptionHandler::OPT_ARG:
  93. (*longOpts).has_arg = optional_argument;
  94. break;
  95. case OptionHandler::NO_ARG:
  96. (*longOpts).has_arg = no_argument;
  97. break;
  98. default:
  99. abort();
  100. }
  101. if ((*first)->getShortName() == 0) {
  102. (*longOpts).flag = plopt;
  103. (*longOpts).val = (*first)->getPref()->i;
  104. }
  105. else {
  106. (*longOpts).flag = nullptr;
  107. (*longOpts).val = (*first)->getShortName();
  108. }
  109. ++longOpts;
  110. }
  111. }
  112. (*longOpts).name = nullptr;
  113. (*longOpts).has_arg = 0;
  114. (*longOpts).flag = nullptr;
  115. (*longOpts).val = 0;
  116. }
  117. } // namespace
  118. namespace {
  119. template <typename InputIterator>
  120. std::string createOptstring(InputIterator first, InputIterator last)
  121. {
  122. std::string str = "";
  123. for (; first != last; ++first) {
  124. if (*first && !(*first)->isHidden()) {
  125. if ((*first)->getShortName() != 0) {
  126. str += (*first)->getShortName();
  127. if ((*first)->getArgType() == OptionHandler::REQ_ARG) {
  128. str += ":";
  129. }
  130. else if ((*first)->getArgType() == OptionHandler::OPT_ARG) {
  131. str += "::";
  132. }
  133. }
  134. }
  135. }
  136. return str;
  137. }
  138. } // namespace
  139. void OptionParser::parseArg(std::ostream& out,
  140. std::vector<std::string>& nonopts, int argc,
  141. char* argv[]) const
  142. {
  143. size_t numPublicOption =
  144. countPublicOption(handlers_.begin(), handlers_.end());
  145. int lopt;
  146. auto longOpts = make_unique<struct option[]>(numPublicOption + 1);
  147. putOptions(longOpts.get(), &lopt, handlers_.begin(), handlers_.end());
  148. std::string optstring = createOptstring(handlers_.begin(), handlers_.end());
  149. while (1) {
  150. int c = getopt_long(argc, argv, optstring.c_str(), longOpts.get(), nullptr);
  151. if (c == -1) {
  152. break;
  153. }
  154. const OptionHandler* op = nullptr;
  155. if (c == 0) {
  156. op = findById(lopt);
  157. }
  158. else if (c != '?') {
  159. op = findByShortName(c);
  160. }
  161. else {
  162. assert(c == '?');
  163. if (optind == 1) {
  164. throw DL_ABORT_EX2("Failed to parse command-line options.",
  165. error_code::OPTION_ERROR);
  166. }
  167. int optlen = strlen(argv[optind - 1]);
  168. const char* optstr = argv[optind - 1];
  169. for (; *optstr == '-'; ++optstr)
  170. ;
  171. int optstrlen = strlen(optstr);
  172. if (optstrlen + 1 >= optlen) {
  173. // If this is short option form (1 '-' prefix), just throw
  174. // error here.
  175. throw DL_ABORT_EX2("Failed to parse command-line options.",
  176. error_code::OPTION_ERROR);
  177. }
  178. // There are 3 situations: 1) completely unknown option 2)
  179. // getopt_long() complained because too few arguments. 3)
  180. // option is ambiguous.
  181. int ambiguous = 0;
  182. for (int i = 1, len = option::countOption(); i < len; ++i) {
  183. PrefPtr pref = option::i2p(i);
  184. const OptionHandler* h = find(pref);
  185. if (h && !h->isHidden()) {
  186. if (strcmp(pref->k, optstr) == 0) {
  187. // Exact match, this means getopt_long detected error
  188. // while handling this option.
  189. throw DL_ABORT_EX2("Failed to parse command-line options.",
  190. error_code::OPTION_ERROR);
  191. }
  192. else if (util::startsWith(pref->k, pref->k + strlen(pref->k), optstr,
  193. optstr + optstrlen)) {
  194. ++ambiguous;
  195. }
  196. }
  197. }
  198. if (ambiguous == 1) {
  199. // This is successfully abbreviated option. So it must be case
  200. // 2).
  201. throw DL_ABORT_EX2("Failed to parse command-line options.",
  202. error_code::OPTION_ERROR);
  203. }
  204. throw UNKNOWN_OPTION_EXCEPTION(argv[optind - 1]);
  205. }
  206. assert(op);
  207. out << op->getName() << "=";
  208. if (optarg) {
  209. out << optarg;
  210. if (op->getEraseAfterParse()) {
  211. for (char* p = optarg; *p != '\0'; ++p) {
  212. *p = '*';
  213. }
  214. }
  215. }
  216. out << "\n";
  217. }
  218. std::copy(argv + optind, argv + argc, std::back_inserter(nonopts));
  219. }
  220. void OptionParser::parse(Option& option, std::istream& is) const
  221. {
  222. std::string line;
  223. while (getline(is, line)) {
  224. if (line.empty() || line[0] == '#') {
  225. continue;
  226. }
  227. auto nv = util::divide(std::begin(line), std::end(line), '=');
  228. if (nv.first.first == nv.first.second) {
  229. continue;
  230. }
  231. PrefPtr pref = option::k2p(std::string(nv.first.first, nv.first.second));
  232. const OptionHandler* handler = find(pref);
  233. if (handler) {
  234. handler->parse(option, std::string(nv.second.first, nv.second.second));
  235. }
  236. else {
  237. A2_LOG_WARN(fmt("Unknown option: %s", line.c_str()));
  238. }
  239. }
  240. }
  241. void OptionParser::parse(Option& option, const KeyVals& options) const
  242. {
  243. for (const auto& o : options) {
  244. auto pref = option::k2p(o.first);
  245. const OptionHandler* handler = find(pref);
  246. if (handler) {
  247. handler->parse(option, o.second);
  248. }
  249. else {
  250. A2_LOG_WARN(fmt("Unknown option: %s", o.first.c_str()));
  251. }
  252. }
  253. }
  254. void OptionParser::setOptionHandlers(
  255. const std::vector<OptionHandler*>& handlers)
  256. {
  257. for (const auto& h : handlers) {
  258. addOptionHandler(h);
  259. }
  260. }
  261. void OptionParser::addOptionHandler(OptionHandler* handler)
  262. {
  263. size_t optId = handler->getPref()->i;
  264. assert(optId < handlers_.size());
  265. handlers_[optId] = handler;
  266. if (handler->getShortName()) {
  267. shortOpts_[static_cast<unsigned char>(handler->getShortName())] = optId;
  268. }
  269. }
  270. void OptionParser::parseDefaultValues(Option& option) const
  271. {
  272. for (const auto& h : handlers_) {
  273. if (h && !h->getDefaultValue().empty()) {
  274. h->parse(option, h->getDefaultValue());
  275. }
  276. }
  277. }
  278. std::vector<const OptionHandler*> OptionParser::findByTag(uint32_t tag) const
  279. {
  280. std::vector<const OptionHandler*> result;
  281. for (const auto& h : handlers_) {
  282. if (h && !h->isHidden() && h->hasTag(tag)) {
  283. result.push_back(h);
  284. }
  285. }
  286. return result;
  287. }
  288. std::vector<const OptionHandler*>
  289. OptionParser::findByNameSubstring(const std::string& substring) const
  290. {
  291. std::vector<const OptionHandler*> result;
  292. for (const auto& h : handlers_) {
  293. if (h && !h->isHidden()) {
  294. size_t nameLen = strlen(h->getName());
  295. if (std::search(h->getName(), h->getName() + nameLen, substring.begin(),
  296. substring.end()) != h->getName() + nameLen) {
  297. result.push_back(h);
  298. }
  299. }
  300. }
  301. return result;
  302. }
  303. std::vector<const OptionHandler*> OptionParser::findAll() const
  304. {
  305. std::vector<const OptionHandler*> result;
  306. for (const auto& h : handlers_) {
  307. if (h && !h->isHidden()) {
  308. result.push_back(h);
  309. }
  310. }
  311. return result;
  312. }
  313. const OptionHandler* OptionParser::find(PrefPtr pref) const
  314. {
  315. return findById(pref->i);
  316. }
  317. const OptionHandler* OptionParser::findById(size_t id) const
  318. {
  319. if (id >= handlers_.size()) {
  320. return handlers_[0];
  321. }
  322. const OptionHandler* h = handlers_[id];
  323. if (!h || h->isHidden()) {
  324. return handlers_[0];
  325. }
  326. else {
  327. return h;
  328. }
  329. }
  330. const OptionHandler* OptionParser::findByShortName(char shortName) const
  331. {
  332. size_t idx = static_cast<unsigned char>(shortName);
  333. return findById(shortOpts_[idx]);
  334. }
  335. std::shared_ptr<OptionParser> OptionParser::optionParser_;
  336. const std::shared_ptr<OptionParser>& OptionParser::getInstance()
  337. {
  338. if (!optionParser_) {
  339. optionParser_ = std::make_shared<OptionParser>();
  340. optionParser_->setOptionHandlers(
  341. OptionHandlerFactory::createOptionHandlers());
  342. }
  343. return optionParser_;
  344. }
  345. void OptionParser::deleteInstance() { optionParser_.reset(); }
  346. } // namespace aria2