command_options.cc 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962
  1. // Copyright (C) 2012-2013 Internet Systems Consortium, Inc. ("ISC")
  2. //
  3. // Permission to use, copy, modify, and/or distribute this software for any
  4. // purpose with or without fee is hereby granted, provided that the above
  5. // copyright notice and this permission notice appear in all copies.
  6. //
  7. // THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
  8. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
  9. // AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
  10. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  11. // LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
  12. // OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  13. // PERFORMANCE OF THIS SOFTWARE.
  14. #include <config.h>
  15. #include <stdio.h>
  16. #include <stdlib.h>
  17. #include <stdint.h>
  18. #include <unistd.h>
  19. #include <boost/lexical_cast.hpp>
  20. #include <boost/date_time/posix_time/posix_time.hpp>
  21. #include <exceptions/exceptions.h>
  22. #include <dhcp/iface_mgr.h>
  23. #include <dhcp/duid.h>
  24. #include "command_options.h"
  25. using namespace std;
  26. using namespace isc;
  27. namespace isc {
  28. namespace perfdhcp {
  29. CommandOptions&
  30. CommandOptions::instance() {
  31. static CommandOptions options;
  32. return (options);
  33. }
  34. void
  35. CommandOptions::reset() {
  36. // Default mac address used in DHCP messages
  37. // if -b mac=<mac-address> was not specified
  38. uint8_t mac[6] = { 0x0, 0xC, 0x1, 0x2, 0x3, 0x4 };
  39. // Default packet drop time if -D<drop-time> parameter
  40. // was not specified
  41. double dt[2] = { 1., 1. };
  42. // We don't use constructor initialization list because we
  43. // will need to reset all members many times to perform unit tests
  44. ipversion_ = 0;
  45. exchange_mode_ = DORA_SARR;
  46. lease_type_ = ADDRESS_ONLY;
  47. rate_ = 0;
  48. report_delay_ = 0;
  49. clients_num_ = 0;
  50. mac_template_.assign(mac, mac + 6);
  51. duid_template_.clear();
  52. base_.clear();
  53. num_request_.clear();
  54. period_ = 0;
  55. drop_time_set_ = 0;
  56. drop_time_.assign(dt, dt + 2);
  57. max_drop_.clear();
  58. max_pdrop_.clear();
  59. localname_.clear();
  60. is_interface_ = false;
  61. preload_ = 0;
  62. aggressivity_ = 1;
  63. local_port_ = 0;
  64. seeded_ = false;
  65. seed_ = 0;
  66. broadcast_ = false;
  67. rapid_commit_ = false;
  68. use_first_ = false;
  69. template_file_.clear();
  70. rnd_offset_.clear();
  71. xid_offset_.clear();
  72. elp_offset_ = -1;
  73. sid_offset_ = -1;
  74. rip_offset_ = -1;
  75. diags_.clear();
  76. wrapped_.clear();
  77. server_name_.clear();
  78. generateDuidTemplate();
  79. }
  80. bool
  81. CommandOptions::parse(int argc, char** const argv, bool print_cmd_line) {
  82. // Reset internal variables used by getopt
  83. // to eliminate undefined behavior when
  84. // parsing different command lines multiple times
  85. #ifdef __GLIBC__
  86. // Warning: non-portable code. This is due to a bug in glibc's
  87. // getopt() which keeps internal state about an old argument vector
  88. // (argc, argv) from last call and tries to scan them when a new
  89. // argument vector (argc, argv) is passed. As the old vector may not
  90. // be main()'s arguments, but heap allocated and may have been freed
  91. // since, this becomes a use after free and results in random
  92. // behavior. According to the NOTES section in glibc getopt()'s
  93. // manpage, setting optind=0 resets getopt()'s state. Though this is
  94. // not required in our usage of getopt(), the bug still happens
  95. // unless we set optind=0.
  96. //
  97. // Setting optind=0 is non-portable code.
  98. optind = 0;
  99. #else
  100. optind = 1;
  101. #endif
  102. // optreset is declared on BSD systems and is used to reset internal
  103. // state of getopt(). When parsing command line arguments multiple
  104. // times with getopt() the optreset must be set to 1 every time before
  105. // parsing starts. Failing to do so will result in random behavior of
  106. // getopt().
  107. #ifdef HAVE_OPTRESET
  108. optreset = 1;
  109. #endif
  110. opterr = 0;
  111. // Reset values of class members
  112. reset();
  113. // Informs if program has been run with 'h' or 'v' option.
  114. bool help_or_version_mode = initialize(argc, argv, print_cmd_line);
  115. if (!help_or_version_mode) {
  116. validate();
  117. }
  118. return (help_or_version_mode);
  119. }
  120. bool
  121. CommandOptions::initialize(int argc, char** argv, bool print_cmd_line) {
  122. int opt = 0; // Subsequent options returned by getopt()
  123. std::string drop_arg; // Value of -D<value>argument
  124. size_t percent_loc = 0; // Location of % sign in -D<value>
  125. double drop_percent = 0; // % value (1..100) in -D<value%>
  126. int num_drops = 0; // Max number of drops specified in -D<value>
  127. int num_req = 0; // Max number of dropped
  128. // requests in -n<max-drops>
  129. int offset_arg = 0; // Temporary variable holding offset arguments
  130. std::string sarg; // Temporary variable for string args
  131. std::ostringstream stream;
  132. stream << "perfdhcp";
  133. // In this section we collect argument values from command line
  134. // they will be tuned and validated elsewhere
  135. while((opt = getopt(argc, argv, "hv46r:t:R:b:n:p:d:D:l:P:a:L:"
  136. "s:iBc1T:X:O:E:S:I:x:w:e:")) != -1) {
  137. stream << " -" << static_cast<char>(opt);
  138. if (optarg) {
  139. stream << " " << optarg;
  140. }
  141. switch (opt) {
  142. case '1':
  143. use_first_ = true;
  144. break;
  145. case '4':
  146. check(ipversion_ == 6, "IP version already set to 6");
  147. ipversion_ = 4;
  148. break;
  149. case '6':
  150. check(ipversion_ == 4, "IP version already set to 4");
  151. ipversion_ = 6;
  152. break;
  153. case 'a':
  154. aggressivity_ = positiveInteger("value of aggressivity: -a<value>"
  155. " must be a positive integer");
  156. break;
  157. case 'b':
  158. check(base_.size() > 3, "-b<value> already specified,"
  159. " unexpected occurence of 5th -b<value>");
  160. base_.push_back(optarg);
  161. decodeBase(base_.back());
  162. break;
  163. case 'B':
  164. broadcast_ = true;
  165. break;
  166. case 'c':
  167. rapid_commit_ = true;
  168. break;
  169. case 'd':
  170. check(drop_time_set_ > 1,
  171. "maximum number of drops already specified, "
  172. "unexpected 3rd occurence of -d<value>");
  173. try {
  174. drop_time_[drop_time_set_] =
  175. boost::lexical_cast<double>(optarg);
  176. } catch (boost::bad_lexical_cast&) {
  177. isc_throw(isc::InvalidParameter,
  178. "value of drop time: -d<value>"
  179. " must be positive number");
  180. }
  181. check(drop_time_[drop_time_set_] <= 0.,
  182. "drop-time must be a positive number");
  183. drop_time_set_ = true;
  184. break;
  185. case 'D':
  186. drop_arg = std::string(optarg);
  187. percent_loc = drop_arg.find('%');
  188. check(max_pdrop_.size() > 1 || max_drop_.size() > 1,
  189. "values of maximum drops: -D<value> already "
  190. "specified, unexpected 3rd occurence of -D,value>");
  191. if ((percent_loc) != std::string::npos) {
  192. try {
  193. drop_percent =
  194. boost::lexical_cast<double>(drop_arg.substr(0, percent_loc));
  195. } catch (boost::bad_lexical_cast&) {
  196. isc_throw(isc::InvalidParameter,
  197. "value of drop percentage: -D<value%>"
  198. " must be 0..100");
  199. }
  200. check((drop_percent <= 0) || (drop_percent >= 100),
  201. "value of drop percentage: -D<value%> must be 0..100");
  202. max_pdrop_.push_back(drop_percent);
  203. } else {
  204. num_drops = positiveInteger("value of max drops number:"
  205. " -d<value> must be a positive integer");
  206. max_drop_.push_back(num_drops);
  207. }
  208. break;
  209. case 'e':
  210. initLeaseType();
  211. break;
  212. case 'E':
  213. elp_offset_ = nonNegativeInteger("value of time-offset: -E<value>"
  214. " must not be a negative integer");
  215. break;
  216. case 'h':
  217. usage();
  218. return (true);
  219. case 'i':
  220. exchange_mode_ = DO_SA;
  221. break;
  222. case 'I':
  223. rip_offset_ = positiveInteger("value of ip address offset:"
  224. " -I<value> must be a"
  225. " positive integer");
  226. break;
  227. case 'l':
  228. localname_ = std::string(optarg);
  229. initIsInterface();
  230. break;
  231. case 'L':
  232. local_port_ = nonNegativeInteger("value of local port:"
  233. " -L<value> must not be a"
  234. " negative integer");
  235. check(local_port_ >
  236. static_cast<int>(std::numeric_limits<uint16_t>::max()),
  237. "local-port must be lower than " +
  238. boost::lexical_cast<std::string>(std::numeric_limits<uint16_t>::max()));
  239. break;
  240. case 'n':
  241. num_req = positiveInteger("value of num-request:"
  242. " -n<value> must be a positive integer");
  243. if (num_request_.size() >= 2) {
  244. isc_throw(isc::InvalidParameter,
  245. "value of maximum number of requests: -n<value> "
  246. "already specified, unexpected 3rd occurence"
  247. " of -n<value>");
  248. }
  249. num_request_.push_back(num_req);
  250. break;
  251. case 'O':
  252. if (rnd_offset_.size() < 2) {
  253. offset_arg = positiveInteger("value of random offset: "
  254. "-O<value> must be greater than 3");
  255. } else {
  256. isc_throw(isc::InvalidParameter,
  257. "random offsets already specified,"
  258. " unexpected 3rd occurence of -O<value>");
  259. }
  260. check(offset_arg < 3, "value of random random-offset:"
  261. " -O<value> must be greater than 3 ");
  262. rnd_offset_.push_back(offset_arg);
  263. break;
  264. case 'p':
  265. period_ = positiveInteger("value of test period:"
  266. " -p<value> must be a positive integer");
  267. break;
  268. case 'P':
  269. preload_ = nonNegativeInteger("number of preload packets:"
  270. " -P<value> must not be "
  271. "a negative integer");
  272. break;
  273. case 'r':
  274. rate_ = positiveInteger("value of rate:"
  275. " -r<value> must be a positive integer");
  276. break;
  277. case 'R':
  278. initClientsNum();
  279. break;
  280. case 's':
  281. seed_ = static_cast<unsigned int>
  282. (nonNegativeInteger("value of seed:"
  283. " -s <seed> must be non-negative integer"));
  284. seeded_ = seed_ > 0 ? true : false;
  285. break;
  286. case 'S':
  287. sid_offset_ = positiveInteger("value of server id offset:"
  288. " -S<value> must be a"
  289. " positive integer");
  290. break;
  291. case 't':
  292. report_delay_ = positiveInteger("value of report delay:"
  293. " -t<value> must be a"
  294. " positive integer");
  295. break;
  296. case 'T':
  297. if (template_file_.size() < 2) {
  298. sarg = nonEmptyString("template file name not specified,"
  299. " expected -T<filename>");
  300. template_file_.push_back(sarg);
  301. } else {
  302. isc_throw(isc::InvalidParameter,
  303. "template files are already specified,"
  304. " unexpected 3rd -T<filename> occurence");
  305. }
  306. break;
  307. case 'v':
  308. version();
  309. return (true);
  310. case 'w':
  311. wrapped_ = nonEmptyString("command for wrapped mode:"
  312. " -w<command> must be specified");
  313. break;
  314. case 'x':
  315. diags_ = nonEmptyString("value of diagnostics selectors:"
  316. " -x<value> must be specified");
  317. break;
  318. case 'X':
  319. if (xid_offset_.size() < 2) {
  320. offset_arg = positiveInteger("value of transaction id:"
  321. " -X<value> must be a"
  322. " positive integer");
  323. } else {
  324. isc_throw(isc::InvalidParameter,
  325. "transaction ids already specified,"
  326. " unexpected 3rd -X<value> occurence");
  327. }
  328. xid_offset_.push_back(offset_arg);
  329. break;
  330. default:
  331. isc_throw(isc::InvalidParameter, "unknown command line option");
  332. }
  333. }
  334. // If the IP version was not specified in the
  335. // command line, assume IPv4.
  336. if (ipversion_ == 0) {
  337. ipversion_ = 4;
  338. }
  339. // If template packet files specified for both DISCOVER/SOLICIT
  340. // and REQUEST/REPLY exchanges make sure we have transaction id
  341. // and random duid offsets for both exchanges. We will duplicate
  342. // value specified as -X<value> and -R<value> for second
  343. // exchange if user did not specified otherwise.
  344. if (template_file_.size() > 1) {
  345. if (xid_offset_.size() == 1) {
  346. xid_offset_.push_back(xid_offset_[0]);
  347. }
  348. if (rnd_offset_.size() == 1) {
  349. rnd_offset_.push_back(rnd_offset_[0]);
  350. }
  351. }
  352. // Get server argument
  353. // NoteFF02::1:2 and FF02::1:3 are defined in RFC3315 as
  354. // All_DHCP_Relay_Agents_and_Servers and All_DHCP_Servers
  355. // addresses
  356. check(optind < argc -1, "extra arguments?");
  357. if (optind == argc - 1) {
  358. server_name_ = argv[optind];
  359. stream << " " << server_name_;
  360. // Decode special cases
  361. if ((ipversion_ == 4) && (server_name_.compare("all") == 0)) {
  362. broadcast_ = true;
  363. // Use broadcast address as server name.
  364. server_name_ = DHCP_IPV4_BROADCAST_ADDRESS;
  365. } else if ((ipversion_ == 6) && (server_name_.compare("all") == 0)) {
  366. server_name_ = ALL_DHCP_RELAY_AGENTS_AND_SERVERS;
  367. } else if ((ipversion_ == 6) &&
  368. (server_name_.compare("servers") == 0)) {
  369. server_name_ = ALL_DHCP_SERVERS;
  370. }
  371. }
  372. if (print_cmd_line) {
  373. std::cout << "Running: " << stream.str() << std::endl;
  374. }
  375. // Handle the local '-l' address/interface
  376. if (!localname_.empty()) {
  377. if (server_name_.empty()) {
  378. if (is_interface_ && (ipversion_ == 4)) {
  379. broadcast_ = true;
  380. server_name_ = DHCP_IPV4_BROADCAST_ADDRESS;
  381. } else if (is_interface_ && (ipversion_ == 6)) {
  382. server_name_ = ALL_DHCP_RELAY_AGENTS_AND_SERVERS;
  383. }
  384. }
  385. }
  386. if (server_name_.empty()) {
  387. isc_throw(InvalidParameter,
  388. "without an interface, server is required");
  389. }
  390. // If DUID is not specified from command line we need to
  391. // generate one.
  392. if (duid_template_.size() == 0) {
  393. generateDuidTemplate();
  394. }
  395. return (false);
  396. }
  397. void
  398. CommandOptions::initClientsNum() {
  399. const std::string errmsg =
  400. "value of -R <value> must be non-negative integer";
  401. // Declare clients_num as as 64-bit signed value to
  402. // be able to detect negative values provided
  403. // by user. We would not detect negative values
  404. // if we casted directly to unsigned value.
  405. long long clients_num = 0;
  406. try {
  407. clients_num = boost::lexical_cast<long long>(optarg);
  408. check(clients_num < 0, errmsg);
  409. clients_num_ = boost::lexical_cast<uint32_t>(optarg);
  410. } catch (boost::bad_lexical_cast&) {
  411. isc_throw(isc::InvalidParameter, errmsg);
  412. }
  413. }
  414. void
  415. CommandOptions::initIsInterface() {
  416. is_interface_ = false;
  417. if (!localname_.empty()) {
  418. dhcp::IfaceMgr& iface_mgr = dhcp::IfaceMgr::instance();
  419. if (iface_mgr.getIface(localname_) != NULL) {
  420. is_interface_ = true;
  421. }
  422. }
  423. }
  424. void
  425. CommandOptions::decodeBase(const std::string& base) {
  426. std::string b(base);
  427. boost::algorithm::to_lower(b);
  428. // Currently we only support mac and duid
  429. if ((b.substr(0, 4) == "mac=") || (b.substr(0, 6) == "ether=")) {
  430. decodeMac(b);
  431. } else if (b.substr(0, 5) == "duid=") {
  432. decodeDuid(b);
  433. } else {
  434. isc_throw(isc::InvalidParameter,
  435. "base value not provided as -b<value>,"
  436. " expected -b mac=<mac> or -b duid=<duid>");
  437. }
  438. }
  439. void
  440. CommandOptions::decodeMac(const std::string& base) {
  441. // Strip string from mac=
  442. size_t found = base.find('=');
  443. static const char* errmsg = "expected -b<base> format for"
  444. " mac address is -b mac=00::0C::01::02::03::04 or"
  445. " -b mac=00:0C:01:02:03:04";
  446. check(found == std::string::npos, errmsg);
  447. // Decode mac address to vector of uint8_t
  448. std::istringstream s1(base.substr(found + 1));
  449. std::string token;
  450. mac_template_.clear();
  451. // Get pieces of MAC address separated with : (or even ::)
  452. while (std::getline(s1, token, ':')) {
  453. unsigned int ui = 0;
  454. // Convert token to byte value using std::istringstream
  455. if (token.length() > 0) {
  456. try {
  457. // Do actual conversion
  458. ui = convertHexString(token);
  459. } catch (isc::InvalidParameter&) {
  460. isc_throw(isc::InvalidParameter,
  461. "invalid characters in MAC provided");
  462. }
  463. // If conversion succeeded store byte value
  464. mac_template_.push_back(ui);
  465. }
  466. }
  467. // MAC address must consist of 6 octets, otherwise it is invalid
  468. check(mac_template_.size() != 6, errmsg);
  469. }
  470. void
  471. CommandOptions::decodeDuid(const std::string& base) {
  472. // Strip argument from duid=
  473. std::vector<uint8_t> duid_template;
  474. size_t found = base.find('=');
  475. check(found == std::string::npos, "expected -b<base>"
  476. " format for duid is -b duid=<duid>");
  477. std::string b = base.substr(found + 1);
  478. // DUID must have even number of digits and must not be longer than 64 bytes
  479. check(b.length() & 1, "odd number of hexadecimal digits in duid");
  480. check(b.length() > 128, "duid too large");
  481. check(b.length() == 0, "no duid specified");
  482. // Turn pairs of hexadecimal digits into vector of octets
  483. for (int i = 0; i < b.length(); i += 2) {
  484. unsigned int ui = 0;
  485. try {
  486. // Do actual conversion
  487. ui = convertHexString(b.substr(i, 2));
  488. } catch (isc::InvalidParameter&) {
  489. isc_throw(isc::InvalidParameter,
  490. "invalid characters in DUID provided,"
  491. " expected hex digits");
  492. }
  493. duid_template.push_back(static_cast<uint8_t>(ui));
  494. }
  495. // @todo Get rid of this limitation when we manage add support
  496. // for DUIDs other than LLT. Shorter DUIDs may be useful for
  497. // server testing purposes.
  498. check(duid_template.size() < 6, "DUID must be at least 6 octets long");
  499. // Assign the new duid only if successfully generated.
  500. std::swap(duid_template, duid_template_);
  501. }
  502. void
  503. CommandOptions::generateDuidTemplate() {
  504. using namespace boost::posix_time;
  505. // Duid template will be most likely generated only once but
  506. // it is ok if it is called more then once so we simply
  507. // regenerate it and discard previous value.
  508. duid_template_.clear();
  509. const uint8_t duid_template_len = 14;
  510. duid_template_.resize(duid_template_len);
  511. // The first four octets consist of DUID LLT and hardware type.
  512. duid_template_[0] = static_cast<uint8_t>(static_cast<uint16_t>(isc::dhcp::DUID::DUID_LLT) >> 8);
  513. duid_template_[1] = static_cast<uint8_t>(static_cast<uint16_t>(isc::dhcp::DUID::DUID_LLT) & 0xff);
  514. duid_template_[2] = HWTYPE_ETHERNET >> 8;
  515. duid_template_[3] = HWTYPE_ETHERNET & 0xff;
  516. // As described in RFC3315: 'the time value is the time
  517. // that the DUID is generated represented in seconds
  518. // since midnight (UTC), January 1, 2000, modulo 2^32.'
  519. ptime now = microsec_clock::universal_time();
  520. ptime duid_epoch(from_iso_string("20000101T000000"));
  521. time_period period(duid_epoch, now);
  522. uint32_t duration_sec = htonl(period.length().total_seconds());
  523. memcpy(&duid_template_[4], &duration_sec, 4);
  524. // Set link layer address (6 octets). This value may be
  525. // randomized before sending a packet to simulate different
  526. // clients.
  527. memcpy(&duid_template_[8], &mac_template_[0], 6);
  528. }
  529. uint8_t
  530. CommandOptions::convertHexString(const std::string& text) const {
  531. unsigned int ui = 0;
  532. // First, check if we are dealing with hexadecimal digits only
  533. for (int i = 0; i < text.length(); ++i) {
  534. if (!std::isxdigit(text[i])) {
  535. isc_throw(isc::InvalidParameter,
  536. "The following digit: " << text[i] << " in "
  537. << text << "is not hexadecimal");
  538. }
  539. }
  540. // If we are here, we have valid string to convert to octet
  541. std::istringstream text_stream(text);
  542. text_stream >> std::hex >> ui >> std::dec;
  543. // Check if for some reason we have overflow - this should never happen!
  544. if (ui > 0xFF) {
  545. isc_throw(isc::InvalidParameter, "Can't convert more than"
  546. " two hex digits to byte");
  547. }
  548. return ui;
  549. }
  550. void
  551. CommandOptions::validate() const {
  552. check((getIpVersion() != 4) && (isBroadcast() != 0),
  553. "-B is not compatible with IPv6 (-6)");
  554. check((getIpVersion() != 6) && (isRapidCommit() != 0),
  555. "-6 (IPv6) must be set to use -c");
  556. check((getExchangeMode() == DO_SA) && (getNumRequests().size() > 1),
  557. "second -n<num-request> is not compatible with -i");
  558. check((getIpVersion() == 4) && (getLeaseType() != ADDRESS_ONLY),
  559. "-6 option must be used if lease type other than '-e address-only'"
  560. " is specified");
  561. check(!getTemplateFiles().empty() && (getLeaseType() != ADDRESS_ONLY),
  562. "template files may be only used with '-e address-only'");
  563. check((getExchangeMode() == DO_SA) && (getDropTime()[1] != 1.),
  564. "second -d<drop-time> is not compatible with -i");
  565. check((getExchangeMode() == DO_SA) &&
  566. ((getMaxDrop().size() > 1) || (getMaxDropPercentage().size() > 1)),
  567. "second -D<max-drop> is not compatible with -i\n");
  568. check((getExchangeMode() == DO_SA) && (isUseFirst()),
  569. "-1 is not compatible with -i\n");
  570. check((getExchangeMode() == DO_SA) && (getTemplateFiles().size() > 1),
  571. "second -T<template-file> is not compatible with -i\n");
  572. check((getExchangeMode() == DO_SA) && (getTransactionIdOffset().size() > 1),
  573. "second -X<xid-offset> is not compatible with -i\n");
  574. check((getExchangeMode() == DO_SA) && (getRandomOffset().size() > 1),
  575. "second -O<random-offset is not compatible with -i\n");
  576. check((getExchangeMode() == DO_SA) && (getElapsedTimeOffset() >= 0),
  577. "-E<time-offset> is not compatible with -i\n");
  578. check((getExchangeMode() == DO_SA) && (getServerIdOffset() >= 0),
  579. "-S<srvid-offset> is not compatible with -i\n");
  580. check((getExchangeMode() == DO_SA) && (getRequestedIpOffset() >= 0),
  581. "-I<ip-offset> is not compatible with -i\n");
  582. check((getExchangeMode() != DO_SA) && (isRapidCommit() != 0),
  583. "-i must be set to use -c\n");
  584. check((getRate() == 0) && (getReportDelay() != 0),
  585. "-r<rate> must be set to use -t<report>\n");
  586. check((getRate() == 0) && (getNumRequests().size() > 0),
  587. "-r<rate> must be set to use -n<num-request>\n");
  588. check((getRate() == 0) && (getPeriod() != 0),
  589. "-r<rate> must be set to use -p<test-period>\n");
  590. check((getRate() == 0) &&
  591. ((getMaxDrop().size() > 0) || getMaxDropPercentage().size() > 0),
  592. "-r<rate> must be set to use -D<max-drop>\n");
  593. check((getTemplateFiles().size() < getTransactionIdOffset().size()),
  594. "-T<template-file> must be set to use -X<xid-offset>\n");
  595. check((getTemplateFiles().size() < getRandomOffset().size()),
  596. "-T<template-file> must be set to use -O<random-offset>\n");
  597. check((getTemplateFiles().size() < 2) && (getElapsedTimeOffset() >= 0),
  598. "second/request -T<template-file> must be set to use -E<time-offset>\n");
  599. check((getTemplateFiles().size() < 2) && (getServerIdOffset() >= 0),
  600. "second/request -T<template-file> must be set to "
  601. "use -S<srvid-offset>\n");
  602. check((getTemplateFiles().size() < 2) && (getRequestedIpOffset() >= 0),
  603. "second/request -T<template-file> must be set to "
  604. "use -I<ip-offset>\n");
  605. }
  606. void
  607. CommandOptions::check(bool condition, const std::string& errmsg) const {
  608. // The same could have been done with macro or just if statement but
  609. // we prefer functions to macros here
  610. if (condition) {
  611. isc_throw(isc::InvalidParameter, errmsg);
  612. }
  613. }
  614. int
  615. CommandOptions::positiveInteger(const std::string& errmsg) const {
  616. try {
  617. int value = boost::lexical_cast<int>(optarg);
  618. check(value <= 0, errmsg);
  619. return (value);
  620. } catch (boost::bad_lexical_cast&) {
  621. isc_throw(InvalidParameter, errmsg);
  622. }
  623. }
  624. int
  625. CommandOptions::nonNegativeInteger(const std::string& errmsg) const {
  626. try {
  627. int value = boost::lexical_cast<int>(optarg);
  628. check(value < 0, errmsg);
  629. return (value);
  630. } catch (boost::bad_lexical_cast&) {
  631. isc_throw(InvalidParameter, errmsg);
  632. }
  633. }
  634. std::string
  635. CommandOptions::nonEmptyString(const std::string& errmsg) const {
  636. std::string sarg = optarg;
  637. if (sarg.length() == 0) {
  638. isc_throw(isc::InvalidParameter, errmsg);
  639. }
  640. return sarg;
  641. }
  642. void
  643. CommandOptions::initLeaseType() {
  644. std::string lease_type_arg = optarg;
  645. if (lease_type_arg == "address-only") {
  646. lease_type_ = ADDRESS_ONLY;
  647. } else if (lease_type_arg == "prefix-only") {
  648. lease_type_ = PREFIX_ONLY;
  649. } else {
  650. isc_throw(isc::InvalidParameter, "value of lease-type: -e<lease-type>,"
  651. " must be one of the following: 'address-only' or"
  652. " 'prefix-only'");
  653. }
  654. }
  655. void
  656. CommandOptions::printCommandLine() const {
  657. std::cout << "IPv" << static_cast<int>(ipversion_) << std::endl;
  658. if (exchange_mode_ == DO_SA) {
  659. if (ipversion_ == 4) {
  660. std::cout << "DISCOVER-OFFER only" << std::endl;
  661. } else {
  662. std::cout << "SOLICIT-ADVERETISE only" << std::endl;
  663. }
  664. }
  665. if (rate_ != 0) {
  666. std::cout << "rate[1/s]=" << rate_ << std::endl;
  667. }
  668. if (report_delay_ != 0) {
  669. std::cout << "report[s]=" << report_delay_ << std::endl;
  670. }
  671. if (clients_num_ != 0) {
  672. std::cout << "clients=" << clients_num_ << std::endl;
  673. }
  674. for (int i = 0; i < base_.size(); ++i) {
  675. std::cout << "base[" << i << "]=" << base_[i] << std::endl;
  676. }
  677. for (int i = 0; i < num_request_.size(); ++i) {
  678. std::cout << "num-request[" << i << "]=" << num_request_[i] << std::endl;
  679. }
  680. if (period_ != 0) {
  681. std::cout << "test-period=" << period_ << std::endl;
  682. }
  683. for (int i = 0; i < drop_time_.size(); ++i) {
  684. std::cout << "drop-time[" << i << "]=" << drop_time_[i] << std::endl;
  685. }
  686. for (int i = 0; i < max_drop_.size(); ++i) {
  687. std::cout << "max-drop{" << i << "]=" << max_drop_[i] << std::endl;
  688. }
  689. for (int i = 0; i < max_pdrop_.size(); ++i) {
  690. std::cout << "max-pdrop{" << i << "]=" << max_pdrop_[i] << std::endl;
  691. }
  692. if (preload_ != 0) {
  693. std::cout << "preload=" << preload_ << std::endl;
  694. }
  695. std::cout << "aggressivity=" << aggressivity_ << std::endl;
  696. if (getLocalPort() != 0) {
  697. std::cout << "local-port=" << local_port_ << std::endl;
  698. }
  699. if (seeded_) {
  700. std::cout << "seed=" << seed_ << std::endl;
  701. }
  702. if (broadcast_) {
  703. std::cout << "broadcast" << std::endl;
  704. }
  705. if (rapid_commit_) {
  706. std::cout << "rapid-commit" << std::endl;
  707. }
  708. if (use_first_) {
  709. std::cout << "use-first" << std::endl;
  710. }
  711. for (int i = 0; i < template_file_.size(); ++i) {
  712. std::cout << "template-file[" << i << "]=" << template_file_[i] << std::endl;
  713. }
  714. for (int i = 0; i < xid_offset_.size(); ++i) {
  715. std::cout << "xid-offset[" << i << "]=" << xid_offset_[i] << std::endl;
  716. }
  717. if (elp_offset_ != 0) {
  718. std::cout << "elp-offset=" << elp_offset_ << std::endl;
  719. }
  720. for (int i = 0; i < rnd_offset_.size(); ++i) {
  721. std::cout << "rnd-offset[" << i << "]=" << rnd_offset_[i] << std::endl;
  722. }
  723. if (sid_offset_ != 0) {
  724. std::cout << "sid-offset=" << sid_offset_ << std::endl;
  725. }
  726. if (rip_offset_ != 0) {
  727. std::cout << "rip-offset=" << rip_offset_ << std::endl;
  728. }
  729. if (!diags_.empty()) {
  730. std::cout << "diagnostic-selectors=" << diags_ << std::endl;
  731. }
  732. if (!wrapped_.empty()) {
  733. std::cout << "wrapped=" << wrapped_ << std::endl;
  734. }
  735. if (!localname_.empty()) {
  736. if (is_interface_) {
  737. std::cout << "interface=" << localname_ << std::endl;
  738. } else {
  739. std::cout << "local-addr=" << localname_ << std::endl;
  740. }
  741. }
  742. if (!server_name_.empty()) {
  743. std::cout << "server=" << server_name_ << std::endl;
  744. }
  745. }
  746. void
  747. CommandOptions::usage() const {
  748. std::cout <<
  749. "perfdhcp [-hv] [-4|-6] [-e<lease-type>] [-r<rate>] [-t<report>]\n"
  750. " [-R<range>] [-b<base>] [-n<num-request>] [-p<test-period>]\n"
  751. " [-d<drop-time>] [-D<max-drop>] [-l<local-addr|interface>]\n"
  752. " [-P<preload>] [-a<aggressivity>] [-L<local-port>] [-s<seed>]\n"
  753. " [-i] [-B] [-c] [-1] [-T<template-file>] [-X<xid-offset>]\n"
  754. " [-O<random-offset] [-E<time-offset>] [-S<srvid-offset>]\n"
  755. " [-I<ip-offset>] [-x<diagnostic-selector>] [-w<wrapped>] [server]\n"
  756. "\n"
  757. "The [server] argument is the name/address of the DHCP server to\n"
  758. "contact. For DHCPv4 operation, exchanges are initiated by\n"
  759. "transmitting a DHCP DISCOVER to this address.\n"
  760. "\n"
  761. "For DHCPv6 operation, exchanges are initiated by transmitting a DHCP\n"
  762. "SOLICIT to this address. In the DHCPv6 case, the special name 'all'\n"
  763. "can be used to refer to All_DHCP_Relay_Agents_and_Servers (the\n"
  764. "multicast address FF02::1:2), or the special name 'servers' to refer\n"
  765. "to All_DHCP_Servers (the multicast address FF05::1:3). The [server]\n"
  766. "argument is optional only in the case that -l is used to specify an\n"
  767. "interface, in which case [server] defaults to 'all'.\n"
  768. "\n"
  769. "The default is to perform a single 4-way exchange, effectively pinging\n"
  770. "the server.\n"
  771. "The -r option is used to set up a performance test, without\n"
  772. "it exchanges are initiated as fast as possible.\n"
  773. "\n"
  774. "Options:\n"
  775. "-1: Take the server-ID option from the first received message.\n"
  776. "-4: DHCPv4 operation (default). This is incompatible with the -6 option.\n"
  777. "-6: DHCPv6 operation. This is incompatible with the -4 option.\n"
  778. "-a<aggressivity>: When the target sending rate is not yet reached,\n"
  779. " control how many exchanges are initiated before the next pause.\n"
  780. "-b<base>: The base mac, duid, IP, etc, used to simulate different\n"
  781. " clients. This can be specified multiple times, each instance is\n"
  782. " in the <type>=<value> form, for instance:\n"
  783. " (and default) mac=00:0c:01:02:03:04.\n"
  784. "-d<drop-time>: Specify the time after which a requeqst is treated as\n"
  785. " having been lost. The value is given in seconds and may contain a\n"
  786. " fractional component. The default is 1 second.\n"
  787. "-e<lease-type>: A type of lease being requested from the server. It\n"
  788. " may be one of the following: address-only or prefix-only. The\n"
  789. " former indicates that the regular IP (v4 or v6) will be requested,\n"
  790. " the latter indicates that the IPv6 prefixes will be requested. The\n"
  791. " '-e prefix-only' must not be used with -4.\n"
  792. "-E<time-offset>: Offset of the (DHCPv4) secs field / (DHCPv6)\n"
  793. " elapsed-time option in the (second/request) template.\n"
  794. " The value 0 disables it.\n"
  795. "-h: Print this help.\n"
  796. "-i: Do only the initial part of an exchange: DO or SA, depending on\n"
  797. " whether -6 is given.\n"
  798. "-I<ip-offset>: Offset of the (DHCPv4) IP address in the requested-IP\n"
  799. " option / (DHCPv6) IA_NA option in the (second/request) template.\n"
  800. "-l<local-addr|interface>: For DHCPv4 operation, specify the local\n"
  801. " hostname/address to use when communicating with the server. By\n"
  802. " default, the interface address through which traffic would\n"
  803. " normally be routed to the server is used.\n"
  804. " For DHCPv6 operation, specify the name of the network interface\n"
  805. " via which exchanges are initiated.\n"
  806. "-L<local-port>: Specify the local port to use\n"
  807. " (the value 0 means to use the default).\n"
  808. "-O<random-offset>: Offset of the last octet to randomize in the template.\n"
  809. "-P<preload>: Initiate first <preload> exchanges back to back at startup.\n"
  810. "-r<rate>: Initiate <rate> DORA/SARR (or if -i is given, DO/SA)\n"
  811. " exchanges per second. A periodic report is generated showing the\n"
  812. " number of exchanges which were not completed, as well as the\n"
  813. " average response latency. The program continues until\n"
  814. " interrupted, at which point a final report is generated.\n"
  815. "-R<range>: Specify how many different clients are used. With 1\n"
  816. " (the default), all requests seem to come from the same client.\n"
  817. "-s<seed>: Specify the seed for randomization, making it repeatable.\n"
  818. "-S<srvid-offset>: Offset of the server-ID option in the\n"
  819. " (second/request) template.\n"
  820. "-T<template-file>: The name of a file containing the template to use\n"
  821. " as a stream of hexadecimal digits.\n"
  822. "-v: Report the version number of this program.\n"
  823. "-w<wrapped>: Command to call with start/stop at the beginning/end of\n"
  824. " the program.\n"
  825. "-x<diagnostic-selector>: Include extended diagnostics in the output.\n"
  826. " <diagnostic-selector> is a string of single-keywords specifying\n"
  827. " the operations for which verbose output is desired. The selector\n"
  828. " keyletters are:\n"
  829. " * 'a': print the decoded command line arguments\n"
  830. " * 'e': print the exit reason\n"
  831. " * 'i': print rate processing details\n"
  832. " * 's': print first server-id\n"
  833. " * 't': when finished, print timers of all successful exchanges\n"
  834. " * 'T': when finished, print templates\n"
  835. "-X<xid-offset>: Transaction ID (aka. xid) offset in the template.\n"
  836. "\n"
  837. "DHCPv4 only options:\n"
  838. "-B: Force broadcast handling.\n"
  839. "\n"
  840. "DHCPv6 only options:\n"
  841. "-c: Add a rapid commit option (exchanges will be SA).\n"
  842. "\n"
  843. "The remaining options are used only in conjunction with -r:\n"
  844. "\n"
  845. "-D<max-drop>: Abort the test if more than <max-drop> requests have\n"
  846. " been dropped. Use -D0 to abort if even a single request has been\n"
  847. " dropped. If <max-drop> includes the suffix '%', it specifies a\n"
  848. " maximum percentage of requests that may be dropped before abort.\n"
  849. " In this case, testing of the threshold begins after 10 requests\n"
  850. " have been expected to be received.\n"
  851. "-n<num-request>: Initiate <num-request> transactions. No report is\n"
  852. " generated until all transactions have been initiated/waited-for,\n"
  853. " after which a report is generated and the program terminates.\n"
  854. "-p<test-period>: Send requests for the given test period, which is\n"
  855. " specified in the same manner as -d. This can be used as an\n"
  856. " alternative to -n, or both options can be given, in which case the\n"
  857. " testing is completed when either limit is reached.\n"
  858. "-t<report>: Delay in seconds between two periodic reports.\n"
  859. "\n"
  860. "Errors:\n"
  861. "- tooshort: received a too short message\n"
  862. "- orphans: received a message which doesn't match an exchange\n"
  863. " (duplicate, late or not related)\n"
  864. "- locallimit: reached to local system limits when sending a message.\n"
  865. "\n"
  866. "Exit status:\n"
  867. "The exit status is:\n"
  868. "0 on complete success.\n"
  869. "1 for a general error.\n"
  870. "2 if an error is found in the command line arguments.\n"
  871. "3 if there are no general failures in operation, but one or more\n"
  872. " exchanges are not successfully completed.\n";
  873. }
  874. void
  875. CommandOptions::version() const {
  876. std::cout << "VERSION: " << VERSION << std::endl;
  877. }
  878. } // namespace perfdhcp
  879. } // namespace isc