command_options.cc 40 KB

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