command_options.cc 38 KB

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