command_options.cc 41 KB

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