command_options.cc 40 KB

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