command_options.cc 39 KB

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