OptionParser.cc 11 KB

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