OptionParser.cc 10 KB

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